3

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.

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

4 Comments

eval, better known as evil :/
'eval' is a common misspelling of 'evil'. If eval is the answer, surely you are asking the wrong question. See mywiki.wooledge.org/BashFAQ/048
eval is not always evil. If you have no choice, then you have to use it. On the webpage you posted, there is a section on "Examples of good use of eval" which says "eval has other uses especially when creating variables out of the blue (indirect variable references)."
Just remember: eval should be treated as a last resort, not an alternative, method to accomplish a task.
1

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

2 Comments

Hi. thanks for the answer. unfortunately that is a bashism and not POSIX.
I don't recommend you to use eval, but to rethink your problem, I'm pretty sure you don't need indirection there. But if you really need it, you should use bash (this trick or arrays) or perl

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.