6

I always use $@ when I want all arguments of bash function but recently I just found that $* also works in the same way, and it also can use as array index.

My question is What is difference between $* an $@ in Bash? and which one should I prefer?

fronthem
  • 4,011
  • 8
  • 34
  • 55

2 Answers2

8

The Bash manual is quite clear on this topic:

  • $*

    All of the positional parameters, seen as a single word.

    Note: $* must be quoted.

  • $@

    Same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.

    Note: Of course, $@ should be quoted.

Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69
Manuel Barbe
  • 2,104
  • 16
  • 21
  • How about `$1`, `$2` ...? should I also quote them? – fronthem Aug 26 '15 at 08:56
  • @terces907 ideally, yes. However, if you know for sure that each argument doesn't contain characters from your IFS, you don't need to. As a side note `echo $*` and `echo $@` without any quotation are equivalent – Aserre Aug 26 '15 at 09:18
  • See further http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-variable – tripleee Aug 26 '15 at 09:24
  • @terces907 generally, you should quote *everything* in bash unless you know what you are doing. Variables or backticks not embedded in double quotes will have unwanted "features" in most cases. – betterworld Aug 26 '15 at 09:31
2

There is a historical development here. $* was found to be insufficient, and so $@ was introduced to replace it. There are still situations where $* is useful; but unless you specifically want to break up quoted tokens, you should avoid it.

tripleee
  • 175,061
  • 34
  • 275
  • 318