复制一个包含空元素的 Bash 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17735242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy a Bash array with empty elements
提问by Benjamin Leinweber
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.
我在 bash (ver 4.2.25) 中使用空元素复制数组时遇到问题。当我将一个数组复制到另一个变量中时,它不会同时复制任何空元素。
#!/bin/bash
array=( 'one' '' 'three' )
copy=( ${array[*]} )
IFS=$'\n'
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?
原始数组具有包括空元素在内的所有三个元素,但副本没有。我在这里做错了什么?
回答by Carl Norum
You have a quoting problem and you should be using @, not *. Use:
您有引用问题,您应该使用@,而不是*。用:
copy=( "${array[@]}" )
From the 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. Ifsubscriptis@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 theIFSspecial variable, and${name[@]}expands each element ofnameto a separate word.
可以使用 引用数组的任何元素
${name[subscript]}。需要大括号以避免与路径名扩展发生冲突。如果subscript是@或*,则单词扩展到 的所有成员name。这些下标仅在单词出现在双引号内时才不同。如果单词是双引号,则${name[*]}扩展为单个单词,每个数组成员的值由IFS特殊变量的第一个字符分隔 ,并将 的${name[@]}每个元素扩展name为单独的单词。
Example output after that change:
更改后的示例输出:
--- array (3) ---
one
three
--- copy (3) ---
one
three

