$#构造在bash中意味着什么?

时间:2010-08-27 15:15:23

标签: bash scripting shell syntax

我看到了

foo() {
if [[ $# -lt 1 ]]; then
    return 0 
fi

...

}

使用$#进行比较究竟是什么呢?

3 个答案:

答案 0 :(得分:7)

$#表示传递给脚本的命令行参数

sh-3.2$ cat a.sh
echo $#  #print the number of cmd line args.
sh-3.2$ ./a.sh
0
sh-3.2$ ./a.sh foo
1
sh-3.2$ ./a.sh foo bar
2
sh-3.2$ ./a.sh foo bar baz
3

在函数内部使用时(如在您的情况下),它表示传递给函数的参数数量:

sh-3.2$ cat a.sh
foo() {
        echo $# #print the number of arguments passed to the function.
}
foo 1
foo 1 2
foo 1 2 3

sh-3.2$ ./a.sh
1
2
3

答案 1 :(得分:3)

$#是传递给脚本的参数数量。有关完整列表,请参阅bash(1)手册页的参数部分的特殊参数子部分。

答案 2 :(得分:2)

$# = 传递给函数的参数数量

在你的代码中,如果没有使用至少一个参数调用该函数,函数将返回0。

相关问题