您的标题询问了${array[@]}
与${array[*]}
(均在 内{}
),但随后您询问了$array[*]
与$array[@]
(均无{}
),这有点令人困惑。我会回答两个(内{}
):
当您引用数组变量并@
用作下标时,数组的每个元素都将扩展为其完整内容,而不管该$IFS
内容中可能存在的空格(实际上是其中一个)。当您使用星号 ( *
) 作为下标时(不管它是否被引用),它可能会扩展为通过在 处分解每个数组元素的内容而创建的新内容$IFS
。
Here's the example script:
#!/bin/sh
myarray[0]="one"
myarray[1]="two"
myarray[3]="three four"
echo "with quotes around myarray[*]"
for x in "${myarray[*]}"; do
echo "ARG[*]: '$x'"
done
echo "with quotes around myarray[@]"
for x in "${myarray[@]}"; do
echo "ARG[@]: '$x'"
done
echo "without quotes around myarray[*]"
for x in ${myarray[*]}; do
echo "ARG[*]: '$x'"
done
echo "without quotes around myarray[@]"
for x in ${myarray[@]}; do
echo "ARG[@]: '$x'"
done
And here's it's output:
with quotes around myarray[*]
ARG[*]: 'one two three four'
with quotes around myarray[@]
ARG[@]: 'one'
ARG[@]: 'two'
ARG[@]: 'three four'
without quotes around myarray[*]
ARG[*]: 'one'
ARG[*]: 'two'
ARG[*]: 'three'
ARG[*]: 'four'
without quotes around myarray[@]
ARG[@]: 'one'
ARG[@]: 'two'
ARG[@]: 'three'
ARG[@]: 'four'
I personally usually want "${myarray[@]}"
. Now, to answer the second part of your question, ${array[@]}
versus $array[@]
.
Quoting the bash docs, which you quoted:
The braces are required to avoid conflicts with the shell's filename expansion operators.
$ myarray=
$ myarray[0]="one"
$ myarray[1]="two"
$ echo ${myarray[@]}
one two
But, when you do $myarray[@]
, the dollar sign is tightly bound to myarray
so it is evaluated before the [@]
. For example:
$ ls $myarray[@]
ls: cannot access one[@]: No such file or directory
But, as noted in the documentation, the brackets are for filename expansion, so let's try this:
$ touch one@
$ ls $myarray[@]
one@
Now we can see that the filename expansion happened after the $myarray
exapansion.
And one more note, $myarray
without a subscript expands to the first value of the array:
$ myarray[0]="one four"
$ echo $myarray[5]
one four[5]