Differences in bash scripts between $@ and $*
Which are the differences between $@
and $*
?
For example I see no differences here:
#! /bin/bash
echo with star: $*
echo with at sign: $@
When they're not quoted, there is no difference between $@
and $*
. Both are equal to $1
$2
… But don't do this.
With double quotes, "$@"
expands each element as an argument:
"$1"
"$2"
…
while "$*"
expands to all elements merged into one argument:
"$1c$2c..."
where c
is the first character of IFS
. If you unset IFS
, c
will be a space.
You almost always want "$@"
. The same goes for arrays: "${myarray[@]}"
@sputnick has the right answer. To demonstrate with an example:\
# use two positional parameters, each with whitespace
set -- "one two" "three four"
# demonstrate the various forms with the default $IFS
echo '$*:'
printf ">%s<\n" $*
echo '$@:'
printf ">%s<\n" $@
echo '"$*":'
printf ">%s<\n" "$*"
echo '"$@":'
printf ">%s<\n" "$@"
# now with a custom $IFS
(
IFS=:
echo '$*:'
printf ">%s<\n" $*
echo '$@:'
printf ">%s<\n" $@
echo '"$*":'
printf ">%s<\n" "$*"
echo '"$@":'
printf ">%s<\n" "$@"
)
outputs
$*:
>one<
>two<
>three<
>four<
$@:
>one<
>two<
>three<
>four<
"$*":
>one two three four<
"$@":
>one two<
>three four<
$*:
>one two<
>three four<
$@:
>one two<
>three four<
"$*":
>one two:three four<
"$@":
>one two<
>three four<