arrays - 复制一个包含空元素的 Bash 数组

标签 arrays bash copy

我在 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. If subscript is @ 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 IFS special variable, and ${name[@]} expands each element of name to a separate word.

更改后的示例输出:

--- array (3) ---
one

three

--- copy (3) ---
one

three

关于arrays - 复制一个包含空元素的 Bash 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17735242/

相关文章:

java - 用Java读取和破坏CSV文件:

css - 将某行 CSS 对准特定标签

python - 将列表的元素复制回 Python 中的列表

php - 将 PHP "grouped"数组转换为 "segmented"数组

java - 为什么我的数组只打印一半的值

ruby - 用于 Unix 命令管道的 Ruby 的 `Object#tap` 的惯用模拟?

bash - 在bash脚本中减去两个时间戳

linux - 使用Bash脚本通过SSH输出服务器上的所有文件夹

Python:变量的副本

c - 在查找最大对和时使用指针