shell脚本中$*的含义是什么?

shell脚本中$*的含义是什么?

在 shell 脚本文件中我看到“$*”,它是什么意思以及我们什么时候必须使用它?

答案1

bash(1)……

特殊参数

shell 对几个参数进行了特殊处理。这些参数仅供参考;不允许向他们分配。

* 扩展到位置参数,从 1 开始。当扩展发生在双引号内时,它会扩展为单个单词,每个参数的值由IFS特殊变量的第一个字符分隔。即,"$*"相当于"$1c$2c…",其中 c 是变量值的第一个字符IFS。如果IFS未设置,参数之间用空格分隔。如果IFS为 null,则连接参数而不插入分隔符。

@ 扩展到位置参数,从 1 开始。当扩展发生在双引号内时,每个参数都会扩展为一个单独的单词。即,"$@"相当于"$1" "$2" …。如果双引号扩展发生在单词内,则第一个参数的扩展与原始单词的开头部分连接,最后一个参数的扩展与原始单词的最后部分连接。当没有位置参数时,"$@"扩展$@为空(即,它们被删除)。

基本上,$*是一个特殊变量,其值是脚本(或 shell 函数)的参数。大多数时候,"$@"更合适。

答案2

这对应于传递给脚本的所有参数。在您的示例中,它用引号引起来;这很重要,因为引号封装了参数之间的(大概)空格。在 shell 脚本中省略引号通常会导致错误。

这里,以 bash 为例,摘自联机帮助页:

 *      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.

干杯

SC。

相关内容