0

How do I solve this in bash

I have a variable called `

DEV_IP=192.168.0.1

I have another variable called

ENV_NAME=DEV

How would I call ENV_NAME to get the IP Addess ?

like:

echo ${ENV_NAME}_IP

This is what I get when I run

echo ${"$ENV"_IP}
-bash: ${"$ENV"_IP}: bad substitution
Barmar
  • 741,623
  • 53
  • 500
  • 612
Kris
  • 1
  • 1

1 Answers1

1

You can use Bash's metavariable syntax (indirect expansion as they call it) if you add a step:

KEY="${ENV_NAME}_IP"
echo ${!KEY}

With variables as you have, outputs:

192.168.0.1

From the TLDP entry on Shell paramter and variable expansion:

If the first character of "PARAMETER" is an exclamation point, Bash uses the value of the variable formed from the rest of "PARAMETER" as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of "PARAMETER" itself. This is known as indirect expansion.

declension
  • 4,110
  • 22
  • 25