复制带有空元素的 Bash 数组 [英] Copy a Bash array with empty elements
问题描述
我在 bash(4.2.25 版)复制带有空元素的数组时遇到问题.当我将数组复制到另一个变量中时,它不会随之复制任何空元素.
I'm having problems in bash (ver 4.2.25) copying arrays with empty elements. When I make a copy of an array into another variable, it does not copy any empty elements along with it.
#!/bin/bash
array=( 'one' '' 'three' )
copy=( ${array[*]} )
IFS=$'
'
echo "--- array (${#array[*]}) ---"
echo "${array[*]}"
echo
echo "--- copy (${#copy[*]}) ---"
echo "${copy[*]}"
当我这样做时,输出如下:
When I do this, here is the output:
--- array (3) ---
one
three
--- copy (2) ---
one
three
原始数组包含所有三个元素,包括空元素,但副本没有.我在这里做错了什么?
The original array has all three elements including the empty element, but the copy does not. What am I doing wrong here?
推荐答案
你有一个引用问题,你应该使用 @
,而不是 *
.使用:
You have a quoting problem and you should be using @
, not *
. Use:
copy=( "${array[@]}" )
来自 bash(1)
手册页:
From the bash(1)
man page:
可以使用 ${name[subscript]}
引用数组的任何元素.需要大括号以避免与路径名扩展发生冲突.如果subscript
是 @
或 *
,单词扩展到 name
的所有成员.这些仅当单词出现在双引号中时,下标才会有所不同.如果该单词被双引号括起来,${name[*]}
扩展为单个单词IFS
的第一个字符分隔的每个数组成员的值特殊变量,而 ${name[@]}
将 name
的每个元素扩展为一个单独的单词.
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
这篇关于复制带有空元素的 Bash 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!