*nux: “$@” is how to iterate over arguments in bash script (via: command line – Stack Overflow)
Posted by jpluimers on 2014/03/29
Thanks Robert Gamble, ephemient and Jonathan Leffler. Be sure to read the top two answers and comments for full details.
Until now, I always used $* to pass on arguments from *nux shells (bash, sh, ash, etc.). Works on ESXi as well. But that is not the correct way to do.
But “$@” is the correct way:
- Use “$@” to represent all the arguments:
for var in "$@"
do
echo "$var"
done
- As a shortcut,
for var; do ...; donemeansfor var in "$@"; do ...; done- Basic thesis: “$@” is correct, and $* (unquoted) is almost always wrong. This is because “$@” works fine when arguments contain spaces, and works the same as $* when they don’t. In some circumstances, “$*” is OK too, but “$@” usually (but not always) works in the same places. Unquoted, $@ and $* are equivalent (and almost always wrong).
This next to the following construct makes file processing in *nix a breeze:
for filename in *.7z; do if 7za t $filename 2>&1 > /dev/null; then echo $filename passed; else echo $filename failed; fi; done
–jeroen
via: command line – How to iterate over arguments in bash script – Stack Overflow.






Leave a comment