Paul Sun Paul Sun - 7 months ago 31
Bash Question

Difference between $* and $@ in Bash

Who can help to give a shell script example to show the difference bewteen

$*
and
$@
?

The following is my script, but it can't tell the difference. Anybody can give a good example?

$ cat internalVar.sh
#!/bin/bash
# internalVar.sh var1 var2
echo "\$? = " $?
export IFS="_"
echo "\$@ = " $@ " == several parameters?"
j=1
for i in $@
do
echo "var $j = $i"
j=$((j+1))
done
echo "\$* = " $* " == a single string"
j=1
for i in $*
do
echo "var $j = $i"
j=$((j+1))
done
echo "\$# = " $#
echo "\$0 = " $0
echo "\$$ = " $$


$ export IFS="c"
[$ ./internalVar.sh par1 "par meter 2" par3
$? = 0
$@ = par1 par meter 2 par3 == several parameters?
var 1 = par1
var 2 = par meter 2
var 3 = par3
$* = par1 par meter 2 par3 == a single string
var 1 = par1
var 2 = par meter 2
var 3 = par3
$# = 3
$0 = ./internalVar.sh
$$ = 4638

Answer

How about this:

$ set 'arg1a arg1b' 'arg2a arg2b' 'arg3a arg3b'
$ for arg in "$@"; do echo "$arg"; done
arg1a arg1b
arg2a arg2b
arg3a arg3b
$ for arg in "$*"; do echo "$arg"; done
arg1a arg1b arg2a arg2b arg3a arg3b
$ for arg in $@; do echo "$arg"; done
arg1a
arg1b
arg2a
arg2b
arg3a
arg3b
$ for arg in $*; do echo "$arg"; done
arg1a
arg1b
arg2a
arg2b
arg3a
arg3b

This loops over the expansion, which in the first case "$@" is a separate parameter for each positional parameter, and in the second case "$*" a single string.

The third and fourth case, the unquoted ones, perform word splitting and are no different from each other.

See also the manual, "Special Parameters".