Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "$@" and "$*" when passing arguments to bash function [duplicate]

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.

like image 945
bodacydo Avatar asked Sep 05 '25 12:09

bodacydo


1 Answers

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.

like image 149
rici Avatar answered Sep 10 '25 06:09

rici