Henke
Henke

Reputation: 125

Expand environment variable from variable

I have a code that looks like this:

my_var="MY_FIRST_ENV_VAR"

My question is, how do I get the value from the environment variable MY_ENV_VAR.

I have tried a lot of thing, but the main problem is that my_var is now a string.

The reason I would like to do this is because I have some environment variables that have almost the same name.

MY_FIRST_ENV_VAR=R1.2.3
MY_SECOND_ENV_VAR=R2.3.4

for vari in FIRST SECOND; do
    branch=MY_$( echo $vari )_ENV_VAR;
    echo $branch;
    echo ${branch};
    echo "${branch};
done;

I have tried a couple of other things as well. I my code I just have access to the FIRST and SECOND strings, I need to construct the name of the variable first.

I have looked for quite some time, and maybe I am just looking for the wrong thing.

Upvotes: 3

Views: 9064

Answers (2)

dogbane
dogbane

Reputation: 274532

Try this:

MY_FIRST_ENV_VAR=R1.2.3
MY_SECOND_ENV_VAR=R2.3.4

for vari in FIRST SECOND; do
    varName="MY_${vari}_ENV_VAR"
    branch=${!varName}
    echo "$branch"
done

Output:

R1.2.3
R2.3.4

${!varName} is known as indirect expansion and allows you to expand the variable called varName. Consult the bash man page for details.


If your shell does not support indirect expansion shown above, use eval instead:

MY_FIRST_ENV_VAR=R1.2.3
MY_SECOND_ENV_VAR=R2.3.4

for vari in FIRST SECOND; do
    branch=$(eval "echo \$MY_${vari}_ENV_VAR")
    echo "$branch"
done

Upvotes: 4

Gilles Quénot
Gilles Quénot

Reputation: 184995

Let's show you

MY_FIRST_ENV_VAR=R1.2.3
MY_SECOND_ENV_VAR=R2.3.4

for vari in FIRST SECOND; do
    branch="MY_${vari}_ENV_VAR"
    echo "branch variable: $branch"
    echo "branch variable indirection: ${!branch}"
done

Output

branch variable: MY_FIRST_ENV_VAR
branch variable indirection: R1.2.3
branch variable: MY_SECOND_ENV_VAR
branch variable indirection: R2.3.4

Doc

${!branch} is a variable indirection

Upvotes: 1

Related Questions