Home > Net >  How to substitute array element with a variable in bash?
How to substitute array element with a variable in bash?

Time:07-31

I've got about 10 arrays like so:

array_1=("Mike" "George" "Sam" "1234" "5678")
array_2=("Albert" "Isabel" "Sami" "4567" "9821")
array_3=("Michel" "Tom" "Cathy" "321" "5664")
array_4=("name 1" "name 2" "name 3" "1233" "4567")
array_5=...

To get single array elements (this is needed because not all are used in the script):

name1="${array_1[0]}"
name2="${array_1[1]}"
name3="${array_1[2]}"
number1="${array_1[3]}"
number2="${array_1[4]}"

Sometimes I want to use array_2 (or 3/4..) instead of array_1. To avoid replacing (array_1) in all the lines of the names and numbers, I'm looking to use a simple variable substitution, so tried to replace with different kind of quotes, including:

myarray="array_1" // also tried 'array_1' and $array_1
name1="${myarray[0]}" // also tried "${$!myarray[0]}" and different quotes combinations

At this point I'm a bit confused about how bash quotes and probably indirects may work for this example, none the found answers nor various tries worked so far, aiming to see if there is rather a simple approach to address this or should the way of how arrays are being used here needs to be changed. Any hint is appreciated.

CodePudding user response:

You need to make myarray a nameref with declare -n.

declare -n myarray=array_1

Then you reference it as if it were the named array:

$ echo "${myarray[0]}"
Mike

CodePudding user response:

@Mike

Proceed as per comment from Mark Reed.
I thought of sharing:
    $ cat "73180037.sh"
    #!/bin/bash
    array_1=("Mike" "George" "Sam" "1234" "5678")
    array_2=("Albert" "Isabel" "Sami" "4567" "9821")
    array_3=("Michel" "Tom" "Cathy" "321" "5664")
    array_4=("name 1" "name 2" "name 3" "1233" "4567")
    array_5=...
    for i in {1..5}
    do
        name1=array_$i[0];
        name2=array_$i[1];
        name3=array_$i[2];
        number1=array_$i[3];
        number2=array_$i[4];
        echo ${!name1} ${!name2} ${!name3} ${!name3} ${!number1} ${!number2}
    done

  • Related