I wrote a bash script countArgs.sh as below:
#!/bin/bash
function count
{
echo $#
}
count "arg1 $@"
I expect the output of the script should be the number of its input plus 1, while the result is like this:
./countArgs.sh a b c
3
I wrote a bash script countArgs.sh as below:
#!/bin/bash
function count
{
echo $#
}
count "arg1 $@"
I expect the output of the script should be the number of its input plus 1, while the result is like this:
./countArgs.sh a b c
3
You are getting count 3
because you have enclosed argument list in double quotes here:
count "arg1 $@"
And due to this count
function is getting these 3 arguments only (in each separate line):
arg1 a
b
c
You can get same output if you place this printf
line in your count
function:
count() {
printf "%s\n" "$@"
echo $#
}
Note how first positional argument is arg1 a
instead of arg1
.
If you remove quotes around arg1 $@
and call it as:
count arg1 "$@"
then you will get 4
as output.
Two point:
first, you are echoing inside a function, it means that $#
will give you the number or arguments or your function, not of your script.
Second, you are calling the function with parameter $@
between quotes "
, but $@
already does it by default, so after variable expansion in fact it will be like this:
count "arg1 a" "b" "c"
Run you script with bash -x
and you will see how it is working:
#!/bin/bash -x
function count
{
echo $#
}
count "arg1 $@"