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
3
  • And what is the problem? Commented Mar 14, 2014 at 0: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, which I found on this question. 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. Commented Mar 14, 2014 at 0: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]}. Commented Mar 14, 2014 at 2:51

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.