Bash looping through array of arrays

arrays, bash

Solution

You can use `indirect variable expansion`:

for i in "${Printers[@]}"; do
    j="$i[@]"
    a=("${!j}")
    echo "${a[@]}"
done

NMR_hp_color_LaserJet_3700 HP Color LaserJet 3700
303_HP_Color_LaserJet_CP5225n HP Color LaserJet CP5520 Series

Update: To get elements of particular index 1 you can use:

for i in "${Printers[@]}"; do j="$i[@]"; a=("${!j}"); echo "${a[1]}"; done
HP Color LaserJet 3700
HP Color LaserJet CP5520 Series

Problem

I am writing a script in BASH 3.2 I have an array of printers with properties I would like to loop through and I'm not getting anything. Here is how I expected it to work: ``` #!/bin/bash NMR=("NMR_hp_color_LaserJet_3700" "HP Color LaserJet 3700"); R303=("303_HP_Color_LaserJet_CP5225n" 'HP Color LaserJet CP5520 Series'); Printers=("NMR" "R303") for i in "${Printers[@]}" do for x in "${i}" do echo "${x[1]}" done done ``` I found this which is closer as it outputs all the values but I can't target a specific property of the printer: ``` #!/bin/bash NMR=("NMR_hp_color_LaserJet_3700" "HP Color LaserJet 3700"); R303=("303_HP_Color_LaserJet_CP5225n" 'HP Color LaserJet CP5520 Series'); Printers=("NMR" "R303") for i in "${Printers[@]}" do arrayz="$i[@]" for x in "${!arrayz}" do echo "$x"; done done ``` How can I target a specific property ?

Original source