Search code examples
bashshellfor-loopconcatenation

Concatenate strings in Bash to call an array in a For loop


I'm looking to nest a couple For loops in bash to first check one array and then based on that array, check a second array.

#!/bin/sh

domArr=( "ABC" "DEF" "GHI" )
ABCarr=( "1" "2" "3" )
DEFarr=( "4" "5" "6" )
GHIarr=( "7" "8" "9" )

for domain in "${domArr[@]}"
do
    # This should be 'domain = "ABC"'
    for group in "${domain+arr[@]}"
    do
        # This should be 'group = "1"'
    done
done

Solution

  • You may use it like this:

    domArr=( "ABC" "DEF" "GHI" )
    ABCarr=( "1" "2" "3" )
    DEFarr=( "4" "5" "6" )
    GHIarr=( "7" "8" "9" )
    
    for domain in "${domArr[@]}"
    do
        echo "iterating array ${domain}arr ..."
        a="${domain}arr[@]"
        for group in "${!a}"
        do
            echo "$group"
        done
    done
    

    Output:

    iterating array ABCarr ...
    1
    2
    3
    iterating array DEFarr ...
    4
    5
    6
    iterating array GHIarr ...
    7
    8
    9