0

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 ]

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.

3
  • 1
    Use an array or associative array. gnu.org/software/bash/manual/html_node/Arrays.html Commented Jul 19, 2023 at 16:19
  • You can use some eval in there, but it's not really recommended. I can drop an example, give me a sec. Commented Jul 19, 2023 at 16:28
  • Why do you want to end up with multiple scalars Variable1, Variable2, etc. instead of just one array Variable[1], Variable[2], etc.? Commented Jul 19, 2023 at 20:12

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Carl, not familiar with ( eval ) but you gave me a good starting point.
Warning: eval has a tendency to interpret things you didn't expect, leading to really weird bugs. It's better to avoid it whenever possible, and in this case it's entirely possible; see "Dynamic variable names in Bash" and "BashFAQ #6: "How can I use variable variables (indirect variables, pointers, references) or associative arrays?"
Use of eval is generally dangerous, and it's unnecessary here. In addition, the way that it is used here is broken. To see why, try adding 'dark red' (for instance) to the Colors array. eval "Variable${j}=\${Colors[i]}" is safer, but still not a good option.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.