如何在Bash中复制数组?

时间:2013-10-17 01:57:36

标签: arrays bash copy

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

depends=$(cat ~/Depends.txt)

当我尝试解析列表并使用

将其复制到新数组时
for i in "${depends[@]}"; do
   if [ $i #isn't installed ]; then
      newDepends+=("$i")
   fi
done

发生的事情是只有依赖的第一个元素依赖于newDepends。

for i in "${newDepends[@]}"; do
   echo $i
done

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

9 个答案:

答案 0 :(得分:87)

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   

答案 1 :(得分:16)

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

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

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

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

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

对于复制关联数组,Isaac的解决方案效果很好。

答案 2 :(得分: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

另一个:

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

答案 3 :(得分:2)

Bash 4.3开始,您可以执行此操作

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

$ declare -n golf=alpha

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

答案 4 :(得分:1)

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

#!/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

这个的输出是:

One
Three
Go!

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

答案 5 :(得分:0)

问题是要复制函数中的数组以使其在父代码中可见。此解决方案适用于索引数组,并且如果在复制之前将预定义为declare -A ARRAY,则也适用于关联数组。

function array_copy
# $1 original array name
# $2 new array name with the same content
{
    local INDEX
    for INDEX in $(eval echo "\${!$1[@]}")
    do
        eval "$2[\"$INDEX\"]=\"\${$1[$INDEX]}\""
    done
}

答案 6 :(得分:0)

尝试以下操作:arrayClone=("${oldArray[@]}")

这很容易。

答案 7 :(得分:0)

我发现这对我有用(主要是:))...

eval $(declare -p base | sed "s,base,target,")

扩展 sed 命令以根据需要编辑任何开关,例如如果新结构必须是可写的,则编辑掉只读 (-r)。

答案 8 :(得分:-3)

我发现了什么问题。我的if is not installed test是两个用于从文件名中删除多余字符的循环,并且如果它们存在于某个Web服务器上则将它们吐出。它没有做的是删除尾随连字符。因此,当它在线测试它的可用性时,它们被解析出来。因为“文件”存在,但“文件 - ”不存在。

相关问题