bash $@ 和 "$@" 之间有什么区别吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37141039/
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
Is there any difference between $@ and "$@"?
提问by carmellose
Is there any difference between $@
and "$@"
?
有什么区别$@
和"$@"
?
I understand there may be differences for non special characters, but what about the @
sign with input arguments?
我知道非特殊字符可能存在差异,但是@
带有输入参数的符号呢?
回答by fedorqui 'SO stop harming'
Yes!
是的!
$ cat a.sh
echo "$@"
echo $@
Let's run it:
让我们运行它:
$ ./a.sh 2 "3 4" 5
2 3 4 5 # output for "$@"
2 3 4 5 # output for $@ -> spaces are lost!
As you can see, using $@
makes the parameters to "lose" some content when used as a parameter. See -for example- I just assigned a variable, but echo $variable shows something elsefor a detailed explanation of this.
如您所见, using$@
使参数在用作参数时“丢失”了一些内容。参见 - 例如 -我刚刚分配了一个变量,但 echo $variable 显示了其他内容以获取对此的详细说明。
From GNU Bash manual --> 3.4.2 Special Parameters:
@
($@) 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 开始。当扩展发生在双引号内时,每个参数都扩展为一个单独的 word。也就是说,“$@”相当于“$1”“$2”……。如果双引号扩展发生在一个词内,则第一个参数的扩展与原词的开头部分连接,最后一个参数的扩展与原词的最后部分连接。当没有位置参数时,"$@" 和 $@ 扩展为空(即,它们被删除)。
回答by a.peganz
Passing $@ to a command passes all arguments to the command. If an argument contains a space the command would see that argument as two separate ones.
将 $@ 传递给命令会将所有参数传递给命令。如果一个参数包含一个空格,命令会将该参数视为两个单独的参数。
Passing "$@" to a command passes all arguments as quoted strings to the command. The command will see an argument containing whitespace as a single argument containing whitespace.
将“$@”传递给命令将所有参数作为带引号的字符串传递给命令。该命令会将包含空格的参数视为包含空格的单个参数。
To easily visualize the difference write a function that prints all its arguments in a loop, one at a time:
为了轻松地可视化差异,请编写一个函数,在循环中打印其所有参数,一次一个:
#!/bin/bash
loop_print() {
while [[ $# -gt 0 ]]; do
echo "argument: ''"
shift
done
}
echo "#### testing with $@ ####"
loop_print $@
echo "#### testing with \"$@\" ####"
loop_print "$@"
Calling that script with
调用该脚本
<script> "foo bar"
will produce the output
将产生输出
#### testing with $@ ####
argument: 'foo'
argument: 'bar'
#### testing with "$@" ####
argument: 'foo bar'