Understanding "$@" and "$*" Positional Parameters in Shell Script
Understanding “$@” and “$*” Positional Parameters in Shell Script
The Values of the “$@” and “$*” Positional Parameters
The values of $@ and $* are identical, but the values of “$@” and “$*” are different. The expansion of “$@” is a list of strings consisting of the values of the positional parameters. The expansion of “$*” is one long string containing the positional parameter values separated by the first character in the set of delimiters of the IFS variable; for example:
$ cat posparatest1.ksh
#!/bin/ksh
# Script name: posparatest1.ksh
set This is only a test
print 'Here is the $* loop.'
for var in "$*"
do
print "$var"
done
print \n"
print 'Here is the $@ loop.'
for var in "$@"
do
print "$var"
done
$ ./posparatest1.ksh
Here is the $* loop.
This is only a test
Here is the $@ loop.
This
is
only
a
test
“$@” expands to “$1” “$2” “$3” … “$n”; that is, n separate strings.
“$*” expands to “$1x$2x$3x…$n”, where x is the first character in the set of delimiters for the IFS variable. This means that “$*” is one long string.
When you use quotes to group tokens into a string, the string sets the value of a single positional parameter.
$ cat posparatest2.sh
#!/bin/sh
# Script name: posparatest2.sh
set "This is a test" and only a test
echo 'Here is the $* loop output: '
for var in "$*"
do
echo "$var"
done
echo "\n"
echo 'Here is the $@ loop output: '
for var in "$@"
do
echo "$var"
done
$ ./posparatest2.sh
Here is the $* loop output:
This is a test and only a test
Here is the $@ loop output:
This is a test
and
only
a
test