复制一个包含空元素的 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:57:21  来源:igfitidea点击:

Copy a Bash array with empty elements

arraysbashcopy

提问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:

bash(1)手册页

Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with pathname expansion. If subscriptis @or *, the word expands to all members of name. 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 the IFSspecial variable, and ${name[@]}expands each element of nameto a separate word.

可以使用 引用数组的任何元素${name[subscript]}。需要大括号以避免与路径名扩展发生冲突。如果 subscript@*,则单词扩展到 的所有成员name。这些下标仅在单词出现在双引号内时才不同。如果单词是双引号,则${name[*]}扩展为单个单词,每个数组成员的值由IFS特殊变量的第一个字符分隔 ,并将 的${name[@]}每个元素扩展name为单独的单词。

Example output after that change:

更改后的示例输出:

--- array (3) ---
one

three

--- copy (3) ---
one

three

回答by Steven Penny

Starting with Bash 4.3, you can do this

Bash 4.3开始,你可以这样做

$ alpha=(bravo charlie 'delta  3' '' foxtrot)

$ declare -n golf=alpha

$ echo "${golf[2]}"
delta  3