0

I want to evaluate a variable, whose name will need to dynamically evaluate another varuiable, i.e. the var ENVIRONMENT can be either prod, stg, or test, so I have 3 urls:

URL_PROD=https://myproduction.com
URL_STG=https://mystaging.com
URL_TEST=https://mytest.com

so I want to retrieve say the value of URL_STG.

The following does not work

echo $"URL_${ENVIRONMENT^^}"
1

Using a recent bash or ksh93, create an associative array to hold the URLs:

URL=( [prod]=https://myproduction.com
      [stg]=https://mystaging.com
      [test]=https://mytest.com )

url_type=test

echo "${URL[$url_type]}"

This will output the testing URL.

1

Besides the associative arrays' related answer proposed by @Kusalananda I also came up with this:

ENDPOINT=URL_${ENVIRONMENT^^}
MY_URL="${!ENDPOINT}"
0

What works for me is:

eval echo \$URL_${ENVIRONMENT^^}
  • The problem with this is that the value of $ENVIRONMENT has to be sanitized first. If the value is, for example, test;>file, your code will create a file called FILE in the current directory. – Kusalananda Feb 23 '18 at 11:03
  • @Kusalananda - That's a theoretical that isn't relevant to the questioner's use-case. He's (seems to be) processing selecting from a list of URLs. – user1404316 Feb 23 '18 at 11:15
  • That's absolutely true. If one has full control over the contents of the strings that one runs eval over, then there is no problem. – Kusalananda Feb 23 '18 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.