如何在 Bash 中复制数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19417015/
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-10 00:19:42  来源:igfitidea点击:

How to copy an array in Bash?

arraysbashcopy

提问by Kyle R.

I have an array of applications, initialized like this:

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

depends=$(cat ~/Depends.txt)

When I try to parse the list and copy it to a new array using,

当我尝试解析列表并将其复制到一个新数组时,

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

What happens is that only the first element of depends winds up on newDepends.

发生的情况是,只有depends 的第一个元素最终依赖于newDepends。

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

^^ This would output just one thing. So I'm trying to figure out why my for loop is is only moving the first element. The whole list is originally on depends, so it's not that, but I'm all out of ideas.

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

回答by user1088530

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   

回答by niieani

The simplest way to copy a non-associative array in bash is to:

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

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

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

or to add elements to a preexistent array:

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

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

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

Newlines/spaces/IFS in the elements will be preserved.

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

For copying associative arrays, Isaac's solutions work great.

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

回答by Isaac Schwabacher

The solutions given in the other answers won't work for associative arrays, or for arrays with non-contiguous indices. Here are is a more general solution:

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

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

And another:

还有一个:

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

回答by maheshk

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

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

This works easily.

这很容易工作。

回答by imp25

You can copy an array by inserting the elements of the first array into the copy by specifying the index:

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

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

The output of this would be:

其输出将是:

One
Three
Go!

A useful document on bash arrays is on TLDP.

关于 bash 阵列的有用文档位于TLDP 上

回答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

回答by Hiro

Problem is to copy array in function to be visible in parent code. This solution works for indexed arrays and if before copying are predefined as declare -A ARRAY, works also for associative arrays.

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

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

回答by Kyle R.

I've discovered what was wrong.. My if isn't installed test is two for loops that remove excess characters from file names, and spits them out if they exist on a certain web server. What it wasn't doing was removing a trailing hyphen. So, when it tested it online for availability, they were parsed out. Because "file" exists, but "file-" doesn't.

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