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.
Try this:
Output:
${!varName}
is known as indirect expansion and allows you to expand the variable calledvarName
. Consult the bash man page for details.If your shell does not support indirect expansion shown above, use
eval
instead:Let's show you
Output
Doc
${!branch}
is a variable indirection