Skip to content
Advertisement

Shell : create and assign variables inside for loop

i ve this shell script ; it’s a loop which set in the variable “a” each time result :

declare -a names=("one" "two" "three" "four")

    for item in "${names[@]}";
    do 
     a="$(cat <<-EOF
        {
          "NAME": "${item}_ABC",
          "CHANGED": "${item}_CHANGING",
          "VERSION": "${item}_GC",
        }
    EOF
    )"
    done
    echo $a

My Purpose is how to change “a” by a dynamic variable name which be $item_MYPREFIX

(concatination :$item + _MYPREFIX )

So that my code would be generic , something like this :

for item in "${names[@]}";
do 
 $item_MYPREFIX="$(cat <<-EOF
    {
          "NAME": "${item}_ABC",
          "CHANGED": "${item}_CHANGING",
          "VERSION": "${item}_GC",
    }
EOF
)"
done

and i would be able to display each variable : echo $one_MYPREFIX , echo $two_MYPREFIX ….

Of course it’s not alerady working

Suggestions , to crrect it ?

Advertisement

Answer

This is really not best practice, but you can (in bash) do:

$ cat a.sh
#!/bin/bash

declare -a names=("one" "two" "three" "four")

for item in "${names[@]}"; do
        eval "read -d '' ${item}_MYPREFIX" << EOF
    {
          "NAME": "${item}_ABC",
          "CHANGED": "${item}_CHANGING",
          "VERSION": "${item}_GC",
    }
EOF
done

for item in "${names[@]}"; do
        k="${item}_MYPREFIX"
        echo "$k = ${!k}"
done
$ ./a.sh
one_MYPREFIX = {
          "NAME": "one_ABC",
          "CHANGED": "one_CHANGING",
          "VERSION": "one_GC",
    }
two_MYPREFIX = {
          "NAME": "two_ABC",
          "CHANGED": "two_CHANGING",
          "VERSION": "two_GC",
    }
three_MYPREFIX = {
          "NAME": "three_ABC",
          "CHANGED": "three_CHANGING",
          "VERSION": "three_GC",
    }
four_MYPREFIX = {
          "NAME": "four_ABC",
          "CHANGED": "four_CHANGING",
          "VERSION": "four_GC",
    }

I believe the only bashism there (besides the existence of arrays, but several shells have arrays) is the usage of ${!...} indirection, but that’s just for output and is not really necessary. However, since you’re using a shell that supports arrays, you might as well not do this at all. Instead of creating a variable named “two_MYPREFIX”, you ought to create an array and store that value in either index 2, or use an associative array and store in with index “two”. That would be much cleaner than using eval.

Advertisement