Expand environment variable from variable

2019-07-21 03:47发布

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条回答
SAY GOODBYE
2楼-- · 2019-07-21 03:56

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
查看更多
别忘想泡老子
3楼-- · 2019-07-21 03:56

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

查看更多
登录 后发表回答