虽然看起来相当简单,但明显的解决方案有细微差别。
以下代码将涵盖大多数情况:
arr_1=(1 2 3 4)
arr_2=($arr_1)
但是,空字符串不会复制。以下代码:
arr_1=('' '' 3 4)
arr_2=($arr_1)
print -l \
"Array 1 size: $#arr_1" \
"Array 2 size: $#arr_2"
将产生:
Array 1 size: 4
Array 2 size: 2
我将如何获取数组的真实副本?
最佳答案
这将是一个“Array Subscripts”问题,因此您可以正确指定数组下标形式以选择双引号内数组的所有元素(例如 $arr_1):
arr_1=('' '' 3 4)
arr_2=("${arr_1[@]}")
#=> arr_2=("" "" "3" "4")
$arr_1
的每个元素即使是空的也会被正确地用双引号括起来。
A subscript of the form ‘[*]’ or ‘[@]’ evaluates to all elements of an array; there is no difference between the two except when they appear within double quotes.
‘"$foo[*]"’ evaluates to ‘"$foo[1] $foo[2] ..."’, whereas ‘"$foo[@]"’ evaluates to ‘"$foo[1]" "$foo[2]" ...’.
...
When an array parameter is referenced as ‘$name’ (with no subscript) it evaluates to ‘$name[*]’,-- Array Subscripts,
zshparam(1)
而数组中的空元素会根据“Empty argument removal”去掉,所以
arr_2=($arr_1)
#=> arr_2=(${arr_1[*]})
#=> arr_2=(3 4)
在这种情况下,上述行为并不好。
24. Empty argument removal
If the substitution does not appear in double quotes, any resulting zero-length argument, whether from a scalar or an element of an array, is elided from the list of arguments inserted into the command line.-- Empty argument removal, Rules Expansion
zshexpn(1)
https://stackoverflow.com/questions/35838392/