Tuesday, November 2, 2021

[SOLVED] Bash variable of variable and assign to a variable

Issue

I have a scenario as follows:

testing1=acs
testing2=rcs
testing3=mes
testing4=gcp

i need to print the values: acs rcs mes gcp I am using following for loop:

 TotalOutputString=''
 for current_number in {1..${max_number}}
 do
    TotalOutputString="${TotalOutputString}  ${testing$current_number} "
 done

 echo $TotalOutputString

But this is not giving proper output. Its only printing numbers.


Solution

You use ${!key) to indirectly access the variable specified by key. In your case:

TotalOutputString=''
for((i=1; 1<=$max_number; i++)) {
    key="testing$current_number"
    TotalOutputString="${TotalOutputString}  ${!key} "
}
echo $TotalOutputString


Answered By - Allan Wind