What is indirect expansion (`${!var}`) and when is it useful?
AdvancedConceptVariables, quoting and expansions
Answer
${!name} expands the variable whose name is stored in name.
DB_HOST_PROD=db.prod.internal
env=PROD
key="DB_HOST_${env}"
echo "${!key}" # db.prod.internal
echo "${!DB_HOST_*}" # names of all variables starting with DB_HOST_
It is the safe alternative to eval "echo \$$key". For anything more than a lookup, prefer an associative array (declare -A db_host=([prod]=...)) or a nameref (declare -n ref=$key).
More on Variables, quoting and expansions
What are the rules for assigning variables in Bash?BeginnerWhat is the difference between single quotes, double quotes and `$'...'`?BeginnerWhy should you almost always quote variable expansions? Show what goes wrong.BeginnerExplain the difference between `"$@"`, `"$*"`, `$@` and `$*`.IntermediateWhat do `${var:-default}`, `${var:=default}`, `${var:+alt}` and `${var:?msg}` do?IntermediateHow do you strip prefixes and suffixes with parameter expansion?Intermediate