Bash: Difference between $@ and $*
From FVue
Problem
What's the difference between $@
and $*
?
Solution
As a rule of thumb, always use "$@"
. This preserves whitespace, keeps arguments intact and is normally desired. Example:
$ set -- foo bar # Two arguments `foo' and `bar' $ for i in "$@"; do echo $i; done foo bar $ set -- 'foo bar' # Single argument 'foo bar' $ for i in "$@"; do echo $i; done foo bar
The table below shows all different combinations of the example above. And the result is that "$@"
is most intuitive. Also it appears "$@"
is the default behaviour of the empty for-loop: for i; do echo $i; done
.
arguments | for i ..; do echo $i; done |
||||
---|---|---|---|---|---|
in $@ |
in "$@" |
in $* |
in "$*" |
(empty) |
|
# Two arguments `foo' and `bar' |
foo bar |
foo bar |
foo bar |
foo bar | foo bar |
# One argument `foo bar' |
foo bar |
foo bar | foo bar |
foo bar | foo bar |
Table 1: Example output of $@, "$@", $* and "$*" in for-loop. The preferred notation in "$@"
preserves whitespace and keeps arguments intact.
Advertisement