1

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
  • There are some related Q&A for reference: https://stackoverflow.com/questions/3008695/what-is-the-difference-between-and-in-bash https://stackoverflow.com/questions/2761723/what-is-the-difference-between-and-in-shell-scripts https://stackoverflow.com/questions/21071943/difference-between-and-in-bash-script https://superuser.com/questions/694501/what-does-mean-as-a-bash-script-function-parameter – Chenling Zhang Jul 21 '17 at 06:27

2 Answers2

0

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

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 $@"
Azize
  • 4,006
  • 2
  • 22
  • 38