开发者

What does the $# construct mean in bash? [duplicate]

开发者 https://www.devze.com 2023-01-13 23:07 出处:网络
This question already has answers here: What are the special dollar sign shell variables? (4 answers) Closed 6 years ago.
This question already has answers here: What are the special dollar sign shell variables? (4 answers) Closed 6 years ago.

I see

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

...

}

What 开发者_JAVA技巧exactly is it comparing by using $# as it does there?


$# represents the number of command line arguments passed to the script.

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

When used inside a function(as in your case) it represents the number of arguments passed to the function:

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


$# is the number of arguments passed to the script. See the Special Parameters subsection of the PARAMETERS section of the bash(1) man page for the full list.


$# = Number of arguments passed to the function.

in your code, the function will return 0 if the function is not called with one parameter at least.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号