I'm having hard time understanding difference between $@
and $*
when passing them to functions.
Here is example:
function a {
echo "-$1-" "-$2-" "-$3-";
}
function b {
a "$@"
}
function c {
a "$*"
}
If calls:
$ b "hello world" "bye world" "xxx"
It prints:
-hello world- -bye world- -xxx-
If calls:
$ c "hello world" "bye world" "xxx"
It prints:
$ c "hello world" "bye world" "xxx"
-hello world bye world xxx- -- --
What happened? I can't understand difference and what went wrong.
There is no difference between $*
and $@
. Both of them result in the list of arguments being glob-expanded and word-split, so you no longer have any idea about the original arguments. You hardly ever want this.
"$*"
results in a single string, which is all of the arguments joined using the first character of $IFS
as a separator (by default, a space). This is occasionally what you want.
"$@"
results in one string per argument, neither word-split nor glob-expanded. This is usually what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With