0

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.

GrandPa
  • 484
  • 9
  • 28
  • 1
    Why don't you use an array? – Allan Wind Sep 25 '21 at 22:26
  • 1
    Does this answer your question? [Create dynamic variable name bash and get value](https://stackoverflow.com/questions/42437044/create-dynamic-variable-name-bash-and-get-value), or [this](https://stackoverflow.com/q/16553089) or [this](https://unix.stackexchange.com/q/222487) – markp-fuso Sep 25 '21 at 22:29
  • 1
    You shouldn't be getting any numbers; this is a syntax error in `bash`. (You also aren't iterating over the numbers 1 through 4 if you are using `bash`, but rather iterating once with `current_number` set to the literal string `{1..4}`.) – chepner Sep 25 '21 at 22:32
  • 1
    You should use arrays instead of this way – Saboteur Sep 25 '21 at 23:00

1 Answers1

1

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
Allan Wind
  • 23,068
  • 5
  • 28
  • 38