The bash manual says:
Regarding: $*
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..."
, wherec
is the first character of the value of theIFS
variable.
Regarding: $@
When the expansion occurs within double quotes, each parameter expands to a separate word. That is,
"$@"
is equivalent to"$1" "$2" ...
.
Provided the first character of the value of the IFS
variable is in fact a single space, I can't seem to come up with an example where these two special parameters would produce different behavior. Can anyone provide me with an example (again, without changing IFS
) where they would produce different behavior?
My own test, which still baffles me a bit, is as follows:
#!/usr/bin/env bash
# File: test.sh
# set foo and bar in the global environment to $@ and $*
test_expansion () {
foo="$@"
bar="$*"
}
Now testing:
. test.sh
test_expansion a b c d
# foo is $@
# bar is $*
for e in "$foo"; do
echo "$e"
done
# a b c d
for e in "$bar"; do
echo "$e"
done
# a b c d
IFS
*at all.* – Scott - Слава Україні Nov 26 '18 at 20:56"$@"
assigns to separate words doesn't apply there. That's discussed in Unexpected outcome of a=“$@”. – ilkkachu Nov 26 '18 at 21:19$@
is special. Once you assign it to an ordinary variable, you lose that special quality. But try using arrays:foo=("$@")
/bar=("$*")
/set | grep '^foo='
/set | grep '^bar='
. – Scott - Слава Україні Nov 26 '18 at 21:36