Bash数组变量:[@]或[*]?

Ste*_* Lu 3 bash

bash-3.2$ echo astr | sed 'hah' | sed 's/s/z/'
sed: 1: "hah": extra characters at the end of h command
bash-3.2$ echo ${PIPESTATUS[*]}
0 1 0
bash-3.2$ echo astr | sed 'hah' | sed 's/s/z/'
sed: 1: "hah": extra characters at the end of h command
bash-3.2$ PIPERET=("${PIPESTATUS[*]}")
bash-3.2$ echo ${PIPERET[*]}
0 1 0
bash-3.2$
Run Code Online (Sandbox Code Playgroud)

这表明[*]工作正常.但是,这个tut提到要使用[@].

两者都同样有效吗?

Jon*_*ler 8

差异主要在数组元素包含空格等,尤其是多个空格时,并且仅在表达式用双引号括起时才显现:

$ x=( '   a  b  c   ' 'd  e  f' )
$ printf "[%s]\n" "${x[*]}"
[   a  b  c    d  e  f]
$ printf "[%s]\n" "${x[@]}"
[   a  b  c   ]
[d  e  f]
$ printf "[%s]\n" ${x[@]}
[a]
[b]
[c]
[d]
[e]
[f]
$ printf "[%s]\n" ${x[*]}
[a]
[b]
[c]
[d]
[e]
[f]
$
Run Code Online (Sandbox Code Playgroud)

外面的双引号,没有区别.在双引号内,*表示"单个字符串",@表示"单独的数组元素".

它与方式$*$@("$*""$@")工作非常相似.

请参阅bash手册: