4

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 ?

1 Answer 1

3

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
5
  • this gives me item 0 rather than item 1 ? how would I target Item 1
    – mcgrailm
    Commented Jun 4, 2014 at 14:37
  • I have also provided output of above script in my answer. Are you not getting same?
    – anubhava
    Commented Jun 4, 2014 at 14:39
  • I am getting the same output but what I was hoping for is to to tell it which property of printers I want so I should get "HP Color LaserJet 3700" and 'HP Color LaserJet CP5520 Series' if I said I want property 1
    – mcgrailm
    Commented Jun 4, 2014 at 14:42
  • this appears to be giving me property 0
    – mcgrailm
    Commented Jun 4, 2014 at 14:43
  • You can get it by index also, check my updated code.
    – anubhava
    Commented Jun 4, 2014 at 15:08

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.