0

Outside of the code I posted below I defined an array fanrp0[1] and fanrp0[2] I did the same for fans 0 through 3. I'm trying to make fstat change and echo each of the fans in two arrays.

    for (( f=1; f<=2; f++ ))
     do
       for (( f2=0; f2<=3; f2++ ))
        do
          fstat="${(fanrp$f2)[$f]}"
          echo $fstat
        done
     done
Cfoote7
  • 375
  • 2
  • 3
  • 14
  • And what is the problem? – anubhava Mar 14 '14 at 00:00
  • It looks like you're trying to do what bash refers to as an indirect reference, which are apparently fairly difficult and cumbersome to do with array variables, judging by [this Bash FAQ page](http://mywiki.wooledge.org/BashFAQ/006), which I found on [this question](http://stackoverflow.com/questions/11180714/how-to-iterate-over-an-array-using-indirect-reference). You can accomplish what you need with `eval` *somewhat* more easily, as in `eval "fstat=\${fanrp$f2[$f]}"`, but keep in mind that there are some security issues with using `eval`. I'd start by reading that Bash FAQ page I linked to. – Mike Holt Mar 14 '14 at 00:23
  • 1
    Indirect array references are easier once you start thinking of the `[...]` not as indexing syntax, but as part of the name of the variable. If you have an array `foo`, then `foo[0]`, `foo[1]`, etc. are just oddly named variables, each with their own value. Then `x=foo[0]` leads naturally to `${!x}` being equivalent to `${foo[0]}`. – chepner Mar 14 '14 at 02:51

1 Answers1

3

If fanrp0, fanrp1, fanrp2, and fanrp3 are all arrays, you can write your loops as

for (( f=1; f<=2; f++ ))
do
  for (( f2=0; f2<=3; f2++ ))
  do
    x="fanrp$f2[$f]"
    fstat="${!x}"
    echo $fstat
  done
done

Since f2 is used only to generate the array names, a slightly cleaner syntax would be

for f in {1..2}; do
  for arr in fanrp{0..3}; do
    x="$arr[$f]"
    fstat=${!x}
    echo $fstat
  done
done
chepner
  • 497,756
  • 71
  • 530
  • 681
  • The first option actually gave me a bad substitute error, that's what I wrote for my first attempt and I couldn't figure out why I was getting that error. However, I think your second solution made a lot more sense to me, thanks it worked great I wasn't aware of the for arr – Cfoote7 Mar 14 '14 at 04:57