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.

  • 1
    Use an array or associative array. https://www.gnu.org/software/bash/manual/html_node/Arrays.html – Shawn Jul 19 '23 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. – Carl Norum Jul 19 '23 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.? – Ed Morton Jul 19 '23 at 20:12

1 Answers1

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.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • Thank you Carl, not familiar with ( eval ) but you gave me a good starting point. – Bruce Ferjulian Jul 19 '23 at 17:00
  • 2
    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"](https://stackoverflow.com/questions/16553089/dynamic-variable-names-in-bash) and ["BashFAQ #6: "How can I use variable variables (indirect variables, pointers, references) or associative arrays?"](http://mywiki.wooledge.org/BashFAQ/006) – Gordon Davisson Jul 19 '23 at 17:05
  • 1
    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. – pjh Jul 19 '23 at 20:56