Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

BASH: How to define a variable with another variable which is part of the strings name

I am trying to create multiple variables but using a numeric counter as part of the variables sting name. All my attempts so far have been futile. Any help would be appreciated.

#!/bin/bash


Colors=( red    \
         blue   \
         green  \
         yellow )

declare i=0
declare j=1

while (( ${j} < $(( ${#Colors[*]} + 1 )) ))
do
  set Variable${j}=${Colors[i]}
  echo   " Tried to create a variable named [ Variable${j} ] and load it with the value [ ${Colors[i]} ]"
  printf " The value of [ Variable${j} ], is [ %s ]\n\n" Variable${j}
  (( j = j + 1 ))
  (( i = i + 1 ))
done

This is what the script currently outputs.

./test.sh

Tried to create a variable named [ Variable1 ] and load it with the value [ red ]
The value of [ Variable1 ], is [ Variable1 ]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Tried to create a variable named [ Variable2 ] and load it with the value [ blue ]
The value of [ Variable2 ], is [ Variable2 ]

Tried to create a variable named [ Variable3 ] and load it with the value [ green ]
The value of [ Variable3 ], is [ Variable3 ]

Tried to create a variable named [ Variable4 ] and load it with the value [ yellow ]
The value of [ Variable4 ], is [ Variable4 ]

Tried ( quotes, set variable ) and nothing so far worked. If I hard code the variable name, no problem.

>Solution :

Inside your loop:

eval Variable${j}=${Colors[i]}
echo   " Tried to create a variable named [ Variable${j} ] and load it with the value [ ${Colors[i]} ]"
eval echo " The value of [ Variable${j} ], is [ \$Variable${j} ]"

Be careful out there.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading