$@ 和"$@" 有区别吗?

Is there any difference between $@ and "$@"?

$@"$@"有区别吗?

我知道非特殊字符可能会有所不同,但是带有输入参数的 @ 符号呢?

是的!

$ cat a.sh
echo "$@"
echo $@

让我们运行它:

$ ./a.sh 2 "3     4" 5
2 3     4 5                  # output for "$@"
2 3 4 5                      # output for $@  -> spaces are lost!

正如你所看到的,使用$@使得参数在作为参数时成为"lose"一些内容。有关详细说明,请参见 - 例如 -


来自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 "" "" …. 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).

将 $@ 传递给命令会将所有参数传递给该命令。如果一个参数包含一个 space,该命令会将该参数视为两个单独的参数。

将“$@”传递给命令会将所有参数作为带引号的字符串传递给命令。该命令会将包含 whitespace 的参数视为包含 whitespace.

的单个参数

为了更容易地看到差异,编写一个函数,在循环中打印所有参数,一次一个:

#!/bin/bash

loop_print() {
    while [[ $# -gt 0 ]]; do
        echo "argument: ''"
        shift
    done
}

echo "#### testing with $@ ####"
loop_print $@
echo "#### testing with \"$@\" ####"
loop_print "$@"

使用

调用该脚本
<script> "foo bar"

将产生输出

#### testing with $@ ####
argument: 'foo'
argument: 'bar'
#### testing with "$@" ####
argument: 'foo bar'