Bash 中的特殊变量

Bash 中的特殊变量

我知道这些是 bash 使用的一些特殊变量。但我无法理解它们。有人能解释一下这些变量是什么以及如何使用它们吗?

$*

$@

$#

答案1

从命令行调用 shell 脚本时,可以向其传递称为位置参数的附加参数。例如,在命令行中输入以下内容来运行脚本时myscript.sh

./myscript.sh param1 param2

这些变量将具有以下值:

"$0" = "./myscript.sh"
"$1" = "param1"
"$2" = "param2"

变量$#给出了参数的数量,不包括命令。在此示例中:

"$#" = 2

该变量$*将所有参数列为一个单词(添加引号以强调字符串边界):

"$*" = "param1 param2"

该变量$@将每个参数列为单独的带引号的字符串(添加引号以强调字符串边界):

"$@" = "param1" "param2"

请注意,在 bash 中,你几乎总是应该用引号括住变量,因此你应该使用"$@"和 而不是$@。参见本编程指南了解更多信息。

答案2

变量$*&$@是调用脚本(或函数,如果在函数内部)时传递的参数。

"$@"是您通常应该使用的那个:它会扩展为单独的单词,对于传入的参数一对一。

"$*"扩展为由空格分隔的所有参数组成的单个“单词”。

(切勿在不使用引号的情况下使用它们;否则会导致单词分裂和您不想处理的混乱。)

$#是参数的数量(因为它始终是一个数字字符串,所以是否引用它并不重要)

答案3

shell 对几个参数进行了特殊处理。

这些参数只能被引用;不允许对其进行赋值。

* Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c…", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

@ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" …. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing.

# Expands to the number of positional parameters in decimal.

$  Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the invoking shell, not the subshell.

来源:https://www.gnu.org/software/bash/manual/html_node/index.html

答案4

我将通过一个例子来展示这三个特殊变量的用例:

  • $#传递给变量的参数数量:

    $ bash -c 'echo number of args to this script are "$#"' _ hello word
    number of args to this script are 2
    
    • 我们的参数是 hello 和 word,所以“2”是正确的
  • $*将扩展为所有位置参数,如:“$1 $2”:

    $ bash -c 'echo -n "args are: "; printf \"%s\" "$*"' _ hello word
    args are: "hello word"
    
    • 注意“你好词”
  • $@:就像所有位置参数“$1”、“$2”...的数组

    $ bash -c 'echo -n "args are: "; printf \"%s\" "$@"' _ hello word
    args are: "hello""word"
    
    • 注意“你好”这个词

相关内容