How to copy an array in Bash?

后端 未结 8 1918
陌清茗
陌清茗 2020-12-02 15:31

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 arra

相关标签:
8条回答
  • 2020-12-02 15:37
    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   
    
    0 讨论(0)
  • 2020-12-02 15:41

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

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

    or to add elements to a preexistent array:

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

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

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

    0 讨论(0)
  • 2020-12-02 15:42

    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
    
    0 讨论(0)
  • 2020-12-02 15:43

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

    This works easily.

    0 讨论(0)
  • 2020-12-02 15:48

    Starting with Bash 4.3, you can do this

    $ alpha=(bravo charlie 'delta  3' '' foxtrot)
    
    $ declare -n golf=alpha
    
    $ echo "${golf[2]}"
    delta  3
    
    0 讨论(0)
  • 2020-12-02 15:51

    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.

    0 讨论(0)
提交回复
热议问题