问题
Is there any difference between $@
and "$@"
?
I understand there may be differences for non special characters, but what about the @
sign with input arguments?
回答1:
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).
回答2:
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'
来源:https://stackoverflow.com/questions/37141039/is-there-any-difference-between-and