在bash中,$#这个结构代表什么意思?

7

我明白了。

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

...

}

它使用$#进行比较,到底是在比较什么?
3个回答

7
< p > $ # 表示传递给脚本的命令行参数数量。

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

3

$# 是传递给脚本的参数数量。请参阅 bash(1) 手册中 PARAMETERS 部分的 Special Parameters 子部分,以获取完整列表。


2

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接