Bash 中的“$@”和“$*”有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3008695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between "$@" and "$*" in Bash?
提问by Debugger
It seems to me that they both store all the command-line arguments.
在我看来,它们都存储了所有命令行参数。
So is there a difference between the two?
那么两者有区别吗?
回答by Hudson
The difference is subtle; "$*"
creates one argument separated by the $IFS
variable, while "$@"
will expand into separate arguments. As an example, consider:
区别很微妙;"$*"
创建一个由$IFS
变量"$@"
分隔的参数,而将扩展为单独的参数。例如,请考虑:
for i in "$@"; do echo "@ '$i'"; done
for i in "$*"; do echo "* '$i'"; done
When run with multiple arguments:
使用多个参数运行时:
./testvar foo bar baz 'long arg'
@ 'foo'
@ 'bar'
@ 'baz'
@ 'long arg'
* 'foo bar baz long arg'
For more details:
更多细节:
http://www.gnu.org/software/bash/manual/bashref.html#Special-Parameters
http://www.gnu.org/software/bash/manual/bashref.html#Special-Parameters
$*
$*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*"
is equivalent to "$1c$2c..."
, where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
扩展到位置参数,从 1 开始。当扩展发生在双引号内时,它扩展为单个单词,每个参数的值由 IFS 特殊变量的第一个字符分隔。也就是说,"$*"
相当于"$1c$2c..."
,其中 c 是 IFS 变量值的第一个字符。如果未设置 IFS,则参数以空格分隔。如果 IFS 为空,则连接参数时不插入分隔符。
$@
$@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@"
is equivalent to "$1" "$2" ....
If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@"
and $@
expand to nothing (i.e., they are removed).
扩展到位置参数,从 1 开始。当扩展发生在双引号内时,每个参数都扩展为一个单独的词。即"$@"
等价于"$1" "$2" ....
如果双引号扩展发生在一个词内,第一个参数的扩展与原词的开头部分连接,最后一个参数的扩展与原词的最后部分连接单词。当有没有位置参数,"$@"
并且$@
扩大到什么(即,它们被删除)。
回答by Art Swri
A keydifference from my POV is that "$@"
preserves the original number
of arguments. It's the onlyform that does.
与我的 POV 的一个主要区别是"$@"
保留了原始参数数量。这是唯一的形式。
For example, if file my_script contains:
例如,如果文件 my_script 包含:
#!/bin/bash
main()
{
echo 'MAIN sees ' $# ' args'
}
main $*
main $@
main "$*"
main "$@"
### end ###
and I run it like this:
我像这样运行它:
my_script 'a b c' d e
I will get this output:
我会得到这个输出:
MAIN sees 5 args
MAIN sees 5 args
MAIN sees 1 args
MAIN sees 3 args