Parsing/passing command line arguments to a bash script - what is the difference between “$@” and “$*”?

依然范特西╮ 提交于 2019-11-28 10:12:18

"$@" corresponds to "$1" "$2" "$3" etc. "$*" corresponds to "$1 $2 $3" which you do not seem to need.

Without quotes, there is no difference, they both correspond to $1 $2 $3 etc.

$* is all parameters as a single word, $@ is all parameters as individual quoted string.

I usually ends up using "$@", seems to work the best for me.

$* contains a single string composed of all of the arguments separated by the first character of $IFS. Thus, if you set IFS to contain a character that cannot usefully be present in your arguments (e.g. a newline if you're passing filenames), then you can consider $* and "$@" to be functionally equivalent, though they work differently under the hood.

$@ is essentially an array of all of the arguments. When passed in double quotation marks ("$@"), the shell individually wraps each value in the array with double quotes (making it an odd exception to the normal rule of double quotes wrapping the entire expansion of a variable).

IIRC, the behavior of a bare $@ without double quotes is not fully specified in the POSIX spec, so it should be considered undefined behavior. Thus, you should never use a bare $@ without double quotes.

BTW, if you care about System V prior to version 3, there were some ancient quirks in how they handled $@. These are largely of historical interest at this point, but they'll give you some appreciation of how the standard evolved as people ran into problems. :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!