2

I have a question about something similar to this question, but I need to call global variable depending on local one.

Say I want to pass either test, staging, or production as a variable to a script, I might do something like this:

#!/bin/bash
env=$1

export ENV_$env=some_param

echo $ENV_${env}

But the global variable seem not be retrieved at all:

# ./script.sh test
test

The use case for this script is to have provide isolation for processes to work in parallel.

Sergey
  • 23

2 Answers2

2

Based on this answer I believe using

varname="ENV_$env"
echo ${!varname}

could be a solution.

0

Try executing the export in the scope of a call to eval:

eval export ENV_${env}=some_param

This ensures that the shell expands ENV_${env} appropriately to one of your expected names, before trying to assign to it.

You'll also need to use eval when trying to retrieve the value stored in your variable:

eval echo \$ENV_$env

Note the backslash - it prevents the shell from attempting to expand the non-existent variable $ENV_, until after it has expanded the $env part with the builtin eval. It is the result of this expansion that is eventually passed to echo, which receives the full name of your dynamic variable, and expands it to yield the value you stored in it earlier.

D_Bye
  • 13,977
  • 3
  • 44
  • 31