Difference between $* and $@
From raju
applicable | bash scripting
What is the difference between $* and $@
Special parameter | expands to |
---|---|
$* | single string |
$@ | actual array |
They can be used in four ways - $*, $@, "$*", "$@". Most likely, you just need "$@". Using "$*" can cause bugs and even security holes in your software.
Form | Meaning |
---|---|
$* | $1 $2 $3 ... |
$@ | $1 $2 $3 ... |
"$*" | "$1 $2 $3 ..." |
"$@" | "$1" "$2" "$3" ... |
In a for loop | result |
---|---|
$* | the string is broken into words |
$@ | each element of the array is treated as an unquoted string |
"$*" | one long quoted string |
"$@" | each element of the array is treated as a quoted string |
output of
$ ./test.sh one two "three four"
where test.sh is the code snippet below.
code snippet | output |
---|---|
for i in $*; do echo $i done |
one two three four |
for i in $@; do echo $i done |
one two three four |
for i in "$*"; do echo $i done |
one two three four |
for i in "$@"; do echo $i done |
one two three four |
See also:-
- https://eklitzke.org/bash-$%2A-and-$@ - shows a use case where this matters.
- http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_02.html#table_03_03 - There are many special parameters available in bash besides $* and $@. This section describes all those.