1

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
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
PhillyPhoto
  • 103
  • 1
  • 10
  • Make your choice: shebang `#!` should be `#!/bin/bash` or remove `sh` – Gilles Quénot Feb 09 '23 at 16:53
  • 1
    What you want is an _indirect reference_. Use namevars. That said, this code will not ever work with a POSIX-standard `/bin/sh`, which doesn't support arrays at all. As Gilles said, your shebang should _explicitly_ start a shell with the features you need. – Charles Duffy Feb 09 '23 at 16:53
  • See [BashFAQ #6](https://mywiki.wooledge.org/BashFAQ/006) for a general reference on indirect references. In present case, you want `declare -n` to set up a namevar (`declare -n curDomArr="${domain}arr"`, and `unset -n curDomArr` to tear it back down. – Charles Duffy Feb 09 '23 at 16:55

2 Answers2

2

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Simply:

#!/bin/bash

dom=( "ABC" "DEF" "GHI" )
ABC=( "1" "2" "3" )
DEF=( "4" "5" "6" )
GHI=( "7" "8" "9" )

for ((i=0; i<${#dom[@]}; i++)); do
    # This should be 'domain = "ABC"' + "1"
    echo "${dom[i]} ${ABC[i]}"
done

Output

ABC 1
DEF 2
GHI 3
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223