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.

4
  • 1
    Why don't you use an array? Commented Sep 25, 2021 at 22:26
  • 1
    Does this answer your question? Create dynamic variable name bash and get value, or this or this Commented Sep 25, 2021 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}.) Commented Sep 25, 2021 at 22:32
  • 1
    You should use arrays instead of this way Commented Sep 25, 2021 at 23:00

1 Answer 1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.