$# 在 shell 中是什么意思?

Buf*_*lls 26 shell shell-script

$#在shell中是什么意思?

我有代码,例如

if [ $# -eq 0 ]
then
Run Code Online (Sandbox Code Playgroud)

我想了解是什么$#意思,但 Google 搜索对于搜索此类内容非常不利。

mic*_*has 38

您可以随时查看 shell 的手册页。man bash说:

Special Parameters
   #      Expands to the number of positional parameters in decimal.
Run Code Online (Sandbox Code Playgroud)

因此,shell 脚本可以检查使用以下代码给出的参数数量:

if [ "$#" -eq 0 ]; then
  echo "you did not pass any parameter"
fi
Run Code Online (Sandbox Code Playgroud)


小智 14

实际上,

`$` refer to `value of` and
`#` refer to `number of / total number`
Run Code Online (Sandbox Code Playgroud)

所以在一起

`$#` refer to `The value of the total number of command line arguments passed.`
Run Code Online (Sandbox Code Playgroud)

因此,您可以$#像以前一样检查传递的参数/参数的数量并处理任何意外情况。

同样,我们有

`$1` for `value of 1st argument passed`
`$2` for 'value of 2nd argument passed`
Run Code Online (Sandbox Code Playgroud)

等等。


Hau*_*ing 9

那是

  1. 调用脚本的参数数量

  2. 已在脚本中设置的参数数量 set -- foo bar

  3. (在函数中使用时)调用函数的参数数量(set也可以在那里工作)。

这在 bash 手册页的“特殊参数”块中进行了解释。