4

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.

2
  • 1
    "$@" is as many strings as there are arguments; "$*" is a single string. There are many questions that cover this — I'll find one shortly. Commented Dec 3, 2015 at 3:08
  • Thanks @JonathanLeffler that's a good reading. Commented Dec 3, 2015 at 3:13

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.