Shell - $@ and $*

发布时间 2023-11-25 19:06:07作者: ZhangZhihuiAAA
 

In Bash (and all POSIX-like shells), $@ or ${@} is a "special parameter" that expands to a list of all positional parameters (= command-line arguments). It is in that respect similar to $*, but with the addition that it can be double-quoted to expand to a list of individual tokens rather than one string containing all positional parameters separated by spaces(1).


(1) Actually, the arguments are not joined explicitly by "space", but rather by the first character of $IFS, the input field-separator variable, which however defaults to "space" in many shells. In the further text I will still use "space" for simplicity and assume that either you left $IFS at its default or changed it to your needs but know what you do.


So,

  • "$*" is equivalent to "$1 $2 $3 ... " and would be treated as "one word" whereas
  • "$@" is equivalent to "$1" "$2" "$3" ...  and would be treated as "several individual words".

Without quotes, both would simply be a space-separated list of words. The difference becomes important when the command-line arguments themselves are strings with spaces, as in

./my_script.sh parameter1 parameter2 "a whole sentence as parameter"
  • $* or $@ without quotes would expand to a list of seven individual tokens. This is rarely what you want.
  • "$*" would expand to one token consisting of seven space-separated words (parameter1 parameter2 a whole sentence as parameter). This is in most cases not what you want.
  • "$@" would expand to a list of 3 tokens, the first two being parameter1 and parameter2, and the last being the string a whole sentence as parameter including its spaces. This is what you will want in most cases, in particular when you want to use it as a list of tokens (to iterate over, to assign to an array, or to pass to a self-defined function).