Bash - Expanding Variables Names Within Variable Names

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
2

1 Answer

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
0

Your Answer

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

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest