Interview Prep/Shell Scripting/Variables, quoting and expansions

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).

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Variables, quoting and expansions