我在 bash(4.2.25 版)复制具有空元素的数组时遇到问题。当我将一个数组复制到另一个变量中时,它不会复制任何空元素。
#!/bin/bash
array=( 'one' '' 'three' )
copy=( ${array[*]} )
IFS=$'\n'
echo "--- array (${#array[*]}) ---"
echo "${array[*]}"
echo
echo "--- copy (${#copy[*]}) ---"
echo "${copy[*]}"
当我这样做时,输出如下:
--- array (3) ---
one
three
--- copy (2) ---
one
three
原始数组包含所有三个元素,包括空元素,但副本没有。我在这里做错了什么?
最佳答案
你有一个引用问题,你应该使用 @
,而不是 *
。使用:
copy=( "${array[@]}" )
来自bash(1)
man page :
Any element of an array may be referenced using
${name[subscript]}
. The braces are required to avoid conflicts with pathname expansion. Ifsubscript
is@
or*
, the word expands to all members ofname
. These subscripts differ only when the word appears within double quotes. If the word is double-quoted,${name[*]}
expands to a single word with the value of each array member separated by the first character of theIFS
special variable, and${name[@]}
expands each element ofname
to a separate word.
更改后的示例输出:
--- array (3) ---
one
three
--- copy (3) ---
one
three
关于arrays - 复制一个包含空元素的 Bash 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17735242/