In shell scripts, what is the difference between $@
and $*
?
Which one is the preferred way to get the script arguments?
Are there differences between the different shell interpreters about this?
In shell scripts, what is the difference between $@
and $*
?
Which one is the preferred way to get the script arguments?
Are there differences between the different shell interpreters about this?
From here:
$@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them.
Take this script for example (taken from the linked answer):
for var in "$@"
do
echo "$var"
done
Gives this:
$ sh test.sh 1 2 '3 4'
1
2
3 4
Now change "$@"
to $*
:
for var in $*
do
echo "$var"
done
And you get this:
$ sh test.sh 1 2 '3 4'
1
2
3
4
(Answer found by using Google)
"$*"
has one other interesting property. Each argument is separated by the value $IFS
instead of a space.
May 3, 2010 at 23:29
A key difference from my POV is that "$@" preserves the original number of arguments. It's the only form that does. For that reason it is very handy for passing args around with the script.
For example, if file my_script contains:
#!/bin/bash
main()
{
echo 'MAIN sees ' $# ' args'
}
main $*
main $@
main "$*"
main "$@"
### end ###
and I run it like this:
my_script 'a b c' d e
I will get this output:
MAIN sees 5 args
MAIN sees 5 args
MAIN sees 1 args
MAIN sees 3 args
With $@ each parameter is a quoted string. Otherwise it behaves the same.
See: http://tldp.org/LDP/abs/html/internalvariables.html#APPREF
"$@"
first generates a quoted string, and then that the shell then parses it on deciding how to run the next command. It would be more accurate to say that the string concatenation done by $*
is skipped, as is the string-splitting done when $*
is used unquoted. Thus, using "$@"
is not only usually more correct, but it also is less work for the shell to interpret.
May 7, 2012 at 23:01
!abs
in irc://irc.freenode.org/#bash -- The infamous "Advanced" Bash Scripting Guide should be avoided unless you know how to filter out the junk. It will teach you to write bugs, not scripts. In that light, the BashGuide was written: mywiki.wooledge.org/BashGuide
May 7, 2012 at 23:05