Shell – Why file glob expansion is not suppressed

quotingshellwildcards

I have the following script my.sh:

echo $@

Now I want to see file glob expansion, so I do like this and it works OK:

$ bash my.sh *
$ f1 f2 my.sh

Now, I've tried suppress expansion using techniques described in this answer:

$ bash my.sh "*"
$ bash my.sh \*

But I still get listing of all files as the output. Why?

Best Answer

With the first invocation of your script

$ bash my.sh *

the file name globbing is performed by the shell before calling the script.

With the second invocation of your script

$ bash my.sh "*"

the file name globbing is performed in the script when running echo $@.

To avoid this, double quote $@ on that line:

echo "$@"

Further reading: Security implications of forgetting to quote a variable in bash/POSIX shells

Related Question