The difference is
word splitting. The most common case where this matters is if you have file names with spaces in them. Here is my unsophisticated explanation.
- $* arguments are separated by spaces
- "$*" means space does not separate arguments
- $@ arguments are separated by spaces
- "$@" arguments are separated by unquoted spaces
This is all fine and good until you bring
IFS into the mix. I'll leave it to others to go into that except to say that you shouldn't change
IFS from its default value unless you have a very specific need to do so and you remember to change it back immediately.
So here's a short, simple Bash script to demonstrate what's happening.
Code:
#! /bin/bash
echo 'parsing with $*'
i=0
for a in $*
do
i=$((i+1))
echo "arg $i = \`$a'"
done
echo "$i args passed"
echo
echo 'parsing with "$*"'
i=0
for a in "$*"
do
i=$((i+1))
echo "arg $i = \`$a'"
done
echo "$i args passed"
echo
echo 'parsing with $@'
i=0
for a in $@
do
i=$((i+1))
echo "arg $i = \`$a'"
done
echo "$i args passed"
echo
echo 'parsing with "$@"'
i=0
for a in "$@"
do
i=$((i+1))
echo "arg $i = \`$a'"
done
echo "$i args passed"
Here's a sample run.
Code:
foo$ ./parseargs one two
parsing with $*
arg 1 = `one'
arg 2 = `two'
2 args passed
parsing with "$*"
arg 1 = `one two'
1 args passed
parsing with $@
arg 1 = `one'
arg 2 = `two'
2 args passed
parsing with "$@"
arg 1 = `one'
arg 2 = `two'
2 args passed
foo$
What happens when we quote the space between arguments?
Code:
foo$ ./parseargs one\ two
parsing with $*
arg 1 = `one'
arg 2 = `two'
2 args passed
parsing with "$*"
arg 1 = `one two'
1 args passed
parsing with $@
arg 1 = `one'
arg 2 = `two'
2 args passed
parsing with "$@"
arg 1 = `one two'
1 args passed
foo$
What happens when we pass no arguments at all?
Code:
foo$ ./parseargs
parsing with $*
0 args passed
parsing with "$*"
arg 1 = `'
1 args passed
parsing with $@
0 args passed
parsing with "$@"
0 args passed
foo$
Most times you will probably want
"$@", but there may be cases where the others are more desirable.
I invite informative expansions and corrections on all the above.
HTH