In many SO questions and bash tutorials I see that I can access command line args in bash scripts in two ways:
$ ~ >cat testargs.sh
#!/bin/bash
echo "you passed me" $*
echo "you passed me" $@
Which results in:
$ ~> bash testargs.sh arg1 arg2
you passed me arg1 arg2
you passed me arg1 arg2
What is the difference between $*
and $@
?
When should one use the former and when shall one use the latter?
This example let may highlight the differ between "at" and "asterix" while we using them. I declared two arrays "fruits" and "vegetables"
See the following result the code above:
$@ is same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.
Of course, "$@" should be quoted.
http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST
A nice handy overview table from the Bash Hackers Wiki:
where
c
in the third row is the first character of$IFS
, the Internal Field Separator; an environment variable.If the arguments are to be stored in a script variable and the arguments are expected to contain spaces, I wholeheartedly recommend employing a
"$*"
trick with the internal field separator$IFS
set to tab.The difference appears when the special parameters are quoted. Let me illustrate the differences:
one further example on the importance of quoting: note there are 2 spaces between "arg" and the number, but if I fail to quote $word:
and in bash,
"$@"
is the "default" list to iterate over:$*
$@
Source: Bash man