How to copy an array in Bash?

后端 未结 8 1930
陌清茗
陌清茗 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: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.

提交回复
热议问题