Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I see

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

...

}

What exactly is it comparing by using $# as it does there?

like image 325
MattUebel Avatar asked Aug 27 '10 15:08

MattUebel


1 Answers

$# 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
like image 152
codaddict Avatar answered Sep 20 '22 23:09

codaddict