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.

Henke
  • 125
  • 1
  • 6

2 Answers2

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
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • _eval_, better known as _evil_ :/ – Gilles Quénot Feb 28 '13 at 10:31
  • 'eval' is a common misspelling of 'evil'. If eval is the answer, surely you are asking the wrong question. See http://mywiki.wooledge.org/BashFAQ/048 – Gilles Quénot Feb 28 '13 at 10:33
  • `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)." – dogbane Feb 28 '13 at 10:54
  • Just remember: `eval` should be treated as a last resort, not an alternative, method to accomplish a task. – chepner Feb 28 '13 at 13:42
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

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • Hi. thanks for the answer. unfortunately that is a bashism and not POSIX. – Henke Feb 28 '13 at 09:24
  • 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 – Gilles Quénot Feb 28 '13 at 10:35