brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ${!name} reads a bash variable whose name is in another variable

Bash
~/tips/tip-bash-indirect-expansion

prod_url=https://example.com

Pick a setting like prod_url or test_url based on another variable.

Sometimes the name of the variable you need is only known at run time, like prod_url or test_url depending on an argument. eval can do it, but I would rather not.

Put the name in a variable, then read through it with !:

prod_url=https://example.com
test_url=https://test.example.com
env=${1:-test}

name="${env}_url"
echo "deploying to ${!name}"

With prod as the first argument this prints the production URL, otherwise the test one. No eval, so nothing in the argument can run as code.

It is read-only. To set a variable whose name you build, use printf -v "$name" '%s' "$value", or declare -n to make a reference that works both ways.

Two things trip people up. An unknown name, like staging_url that does not exist, gives an empty string without an error, so check the result with ${!name:?} or -z. And the syntax collides with ${!prefix@} and ${!array[@]}, which do something else entirely. When the list of options is fixed, an associative array with declare -A is often clearer than a set of variables with built names.

Further reading: Bash manual: Shell Parameter Expansion

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link