0

In a simple for loop, I'm trying to get it to increment which variable it echos. The unrolled version at the bottom works and does what I want, but how can I get the loop to work the same way?

for x in 0 1 2 3 4 do 
       echo -ne $FVAR$x ":: "
       echo $LVAR$x 
done





        echo -ne $FVAR0 ":: "
        echo $LVAR0
        echo -ne $FVAR1 ":: "
        echo $LVAR1
        echo -ne $FVAR2 ":: "
        echo $LVAR2
        echo -ne $FVAR3 ":: "
        echo $LVAR3
        echo -ne $FVAR4 ":: "
        echo $LVAR4
  • Bash supports array variables. If your index x is a simple integer, that may be something you could consider, referencing them as ${FVAR[0]} or ${LVAR[4]}, etc. – Jim L. Jan 25 at 18:32
  • Given this context, that's fair. The only trouble is the code I'm supporting uses variables in this way because earlier on, exporting must be done, so arrays aren't an option. I should have specified that in the question, but I am hoping to find some way to just have echo see that $FVAR$x should mean $FVAR0 on the first iteration of the loop. – Volumetricsteve Jan 25 at 18:35
1

From the bash manual:-

If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion.

So you need to store the name of the variable you want to expand in a separate variable, eg:-

for x in 0 1 2 3 4
do  fv=FVAR$x
    lv=LVAR$x
    echo ${!fv} ":: " ${!lv}
done

You could alternatively define fv and lv as of type nameref: the code would be similar, except that there is no need for ! to expand the variables:-

declare -n fv
declare -n lv

for x in 0 1 2 3 4
do  fv=FVAR$x
    lv=LVAR$x
    echo $fv ":: " $lv
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.