即使使用双引号也会发生分词

Word splitting happens even with double quotes

根据http://tldp.org/LDP/abs/html/quotingvar.html

Use double quotes to prevent word splitting. An argument enclosed in double quotes presents itself as a single word, even if it contains whitespace separators.

不过,我有

0> /bin/bash --version
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
[...]

1> cat inspect.sh 
#!/bin/bash
echo "first argument is "
echo "second argument is "

2> cat test.sh 
#!/bin/bash
set -x
./inspect.sh "hello $@"

3> ./test.sh alice bob
+ ./inspect.sh 'hello alice' bob
first argument is hello alice
second argument is bob

4> ./test.sh "alice bob"
+ ./inspect.sh 'hello alice bob'
first argument is hello alice bob
second argument is 

我想知道为什么 3> 和 4> 有不同的结果?如何修改 test.sh 让 3> 和 4> 有相同的输出?

答案是$@很特别

来自Bash Reference Manual section 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).

具体来说:

  • 当双引号内发生扩展时,每个参数都会扩展为一个单独的词。

  • 如果双引号展开出现在一个词内,第一个参数的展开与原词的开头部分相连,最后一个参数的展开与原词的末尾相连.

哪个组合让你 "hello " 合并到第一个参数,"" 合并到最后一个参数,但每个参数扩展到它自己的词。

如果您想将所有参数扩展为一个词,那么您需要使用 $*

*

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 "cc…", 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.