0

I am trying to access different versions of an environment variable based on the contents of another variable.

I have tried concatenating the two like below but the order in which they are evaluated does not seem right, is this possible? Or is there a better way of approaching this problem?

MY_VARIABLE_TEST=testVar
MY_VARIABLE_LIVE=liveVar

ENVIRONMENT=TEST

# expecting target to equal testVar
TARGET=$MY_VARIABLE_${ENVIRONMENT}

Thanks in advance for any help

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Andy
  • 101
  • 10
  • 3
    `target_varname=MY_VARIABLE_${ENVIRONMENT}; TARGET=${!target_varname}` – Charles Duffy Apr 16 '20 at 16:06
  • btw, note that these are just regular shell variables, not environment variables, as written here. An *environment* variable is one that's copied to child processes. (Also, note the naming conventions in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html -- all-caps names are used for variables that can modify shell or POSIX-defined utility operation, whereas names with at least one lower-case character are guaranteed safe for applications to use without unwanted side effects on POSIX-compliant shells or tools). – Charles Duffy Apr 16 '20 at 16:07
  • ...also, there's only a limited pool of (kernel-allocated) space shared between environment variables and command-line arguments, so the more (and larger) environment variables you define, the shorter your maximum command-line length is. You don't want to use them unnecessarily; using regular shell variables whenever possible is the Right Thing. – Charles Duffy Apr 16 '20 at 16:09

0 Answers0