views:

98

answers:

2

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 ?

+5  A: 

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)

Mark Byers
`"$*"` has one other interesting property. Each argument is separated by the value `$IFS` instead of a space.
R Samuel Klatchko
It may be worthwhile to explain how the substitutions end up expanded (what the commands look-like afterwards) and why it results in the differing results.
Bert F
+1  A: 

With $@ each parameter is a quoted string. Otherwise it behaves the same.

See: http://tldp.org/LDP/abs/html/internalvariables.html#APPREF

ghills