Monday, September 5, 2022

[SOLVED] Define variable based on loop index in bash

Issue

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?


Solution

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



Answered By - Özgür Murat Sağdıçoğlu
Answer Checked By - Marilyn (WPSolving Volunteer)