0

I've got very simple array consisting of two elements. Now I want to go through this array in for loop and store elements in unique variables with different name. I'm trying something like this:

for i in ${!array[@]};
  do
    element$i=${array[$i]}
    echo "$element{$i}" 
  done

But the result is error message

bash: element0=odm-eureka-cfg: command not found
bash: element1=github: command not found

What am I doing wrong?

vjancich
  • 35
  • 6

3 Answers3

1

Bash just don't understand that you are declaring a variable in that line. You should just put a declare keyword. Also the echo command should be changed. First you should alias that dynamic variable name to some name using declare -n, then use that name.

for i in ${!array[@]};
  do
    declare element$i=${array[$i]}
    declare -n var=element$i
    echo "${var}" 
  done

Note: don't use eval in bash

0

use eval to execute the commands:

for i in ${!array[@]};
do
    cmd="element$i=${array[$i]}"
    eval $cmd
    cmd="echo \${element$i}"
    eval $cmd
done
pppn
  • 66
  • 3
0

This is pointless, arrays actually meant for this. You are just copying the array itself. But for the educational purposes here you go:

# using printf
for i in ${!array[@]}; do
    new_var="element$i"
    printf -v $new_var "${array[$i]}"
    echo "${!new_var}" 
done

# using declare
for i in ${!array[@]}; do
    new_var="element$i"
    declare $new_var="${array[$i]}"
    echo "${!new_var}" 
done

# using read
for i in ${!array[@]}; do
    new_var="element$i"
    read $new_var <<< "${array[$i]}"
    echo "${!new_var}" 
done
Ivan
  • 6,188
  • 1
  • 16
  • 23
  • Thank you for help, but I don't fully understand. Seems to me like it creates still only one variable new_var, just chaning its value. I need to create MULTIPLE UNIQUE variables in the loop, each containing different element of array. So I just want to break array into multiple variables – vjancich Aug 23 '22 at 06:56
  • @vjancich It's creating variables named with current value of `$new_var`. This intermediate `$new_var` is needed to be able to read from those dynamically created vars like this `echo "${!new_var}"`. Coz `echo $element$i` won't work, it'll print only `$i`. – Ivan Aug 23 '22 at 10:47