如何在Bash中复制数组?

Kyl*_* R. 52 arrays bash copy

我有一个应用程序数组,初始化如下:

depends=$(cat ~/Depends.txt)
Run Code Online (Sandbox Code Playgroud)

当我尝试解析列表并使用时将其复制到新数组中,

for i in "${depends[@]}"; do
   if [ $i #isn't installed ]; then
      newDepends+=("$i")
   fi
done
Run Code Online (Sandbox Code Playgroud)

会发生什么是只有依赖的第一个元素依赖于newDepends.

for i in "${newDepends[@]}"; do
   echo $i
done
Run Code Online (Sandbox Code Playgroud)

^^这只会产生一件事.所以我想弄清楚为什么我的for循环只是移动第一个元素.整个列表原本依赖,所以不是这样,但我完全没有想法.

use*_*530 103

a=(foo bar "foo 1" "bar two")  #create an array
b=("${a[@]}")                  #copy the array in another one 

for value in "${b[@]}" ; do    #print the new array 
echo "$value" 
done   
Run Code Online (Sandbox Code Playgroud)

  • 尝试用您的修改来执行命令,你会为什么已了解这是不正确引用没有写......喜欢它shoudl值"FOO 1"将不显示,但它会创建数组foo和1条更多的价值和二,而不是"foo 1"和"bar two" (8认同)
  • 也适用于复制命令行参数,如`b=("$@")`。 (3认同)
  • 可以写b =($ {a [@]})吗? (2认同)
  • @Indicator您将遇到空格问题! (2认同)
  • 如果某些元素为空,这会更改元素的顺序。 (2认同)

nii*_*ani 21

在bash中复制非关联数组的最简单方法是:

arrayClone=("${oldArray[@]}")

或者将元素添加到预先存在的数组:

someArray+=("${oldArray[@]}")

将保留元素中的换行符/空格/ IFS.

对于复制关联数组,Isaac的解决方案非常有用.

  • 嘿@FelipeAlvarez - 确实`!`是多余的,我纠正了我的回答 (2认同)

小智 6

尝试这个:arrayClone=("${oldArray[@]}")

这很容易实现。


小智 5

其他答案中给出的解决方案不适用于关联数组,也不适用于具有非连续索引的数组.这是一个更通用的解决方案:

declare -A arr=([this]=hello [\'that\']=world [theother]='and "goodbye"!')
temp=$(declare -p arr)
eval "${temp/arr=/newarr=}"

diff <(echo "$temp") <(declare -p newarr | sed 's/newarr=/arr=/')
# no output
Run Code Online (Sandbox Code Playgroud)

而另一个:

declare -A arr=([this]=hello [\'that\']=world [theother]='and "goodbye"!')
declare -A newarr
for idx in "${!arr[@]}"; do
    newarr[$idx]=${arr[$idx]}
done

diff <(echo "$temp") <(declare -p newarr | sed 's/newarr=/arr=/')
# no output
Run Code Online (Sandbox Code Playgroud)

  • 你的第一个解决方案不能成为一个函数,因为 `eval "declare -A newarr=…"` 将有效地声明一个 *local* 数组 `newarr` 来遮蔽父环境中的真实变量。可以选择删除“declare -A”,以便只留下“newarr=…”,但是沿着这条路径存在逃逸问题。 (2认同)

imp*_*p25 3

您可以通过指定索引将第一个数组的元素插入到副本中来复制数组:

#!/bin/bash

array=( One Two Three Go! );
array_copy( );

let j=0;
for (( i=0; i<${#array[@]}; i++)
do
    if [[ $i -ne 1 ]]; then # change the test here to your 'isn't installed' test
        array_copy[$j]="${array[$i]}
        let i+=1;
    fi
done

for k in "${array_copy[@]}"; do
    echo $k
done
Run Code Online (Sandbox Code Playgroud)

其输出将是:

One
Three
Go!
Run Code Online (Sandbox Code Playgroud)

关于 bash 数组的有用文档位于TLDP上。