5

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.

bodacydo
  • 75,521
  • 93
  • 229
  • 319

1 Answers1

12

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.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
rici
  • 234,347
  • 28
  • 237
  • 341