Accessing bash command line args $@ vs $* Accessing bash command line args $@ vs $* bash bash

Accessing bash command line args $@ vs $*


The difference appears when the special parameters are quoted. Let me illustrate the differences:

$ set -- "arg  1" "arg  2" "arg  3"$ for word in $*; do echo "$word"; donearg1arg2arg3$ for word in $@; do echo "$word"; donearg1arg2arg3$ for word in "$*"; do echo "$word"; donearg  1 arg  2 arg  3$ for word in "$@"; do echo "$word"; donearg  1arg  2arg  3

one further example on the importance of quoting: note there are 2 spaces between "arg" and the number, but if I fail to quote $word:

$ for word in "$@"; do echo $word; donearg 1arg 2arg 3

and in bash, "$@" is the "default" list to iterate over:

$ for word; do echo "$word"; donearg  1arg  2arg  3


A nice handy overview table from the Bash Hackers Wiki:

SyntaxEffective result
$*$1 $2 $3 … ${N}
$@$1 $2 $3 … ${N}
"$*""$1c$2c$3c…c${N}"
"$@""$1" "$2" "$3" … "${N}"

where c in the third row is the first character of $IFS, the Input Field Separator, a shell variable.

If the arguments are to be stored in a script variable and the arguments are expected to contain spaces, I wholeheartedly recommend employing a "$*" trick with the input field separator set to tab IFS=$'\t'.


$*

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

$@

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Source: Bash man