Is there any difference between $@ and “$@”? [duplicate]

若如初见. 提交于 2019-12-05 04:58:50
fedorqui

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 else for a detailed explanation of this.


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).

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: '$1'"
        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'
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!