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: ${!PREFIX@} lists every bash variable whose name starts the same

Bash
~/tips/tip-bash-prefix-variable-names

APP_HOST=example.com

Loop over all settings like APP_PORT and APP_HOST without naming each one.

When a script reads its settings from variables like APP_HOST, APP_PORT and APP_USER, printing all of them for a debug line usually means a hand-written list that is always out of date.

Bash can list the variable names for you:

APP_HOST=example.com
APP_PORT=8080
echo "${!APP_@}"
# APP_HOST APP_PORT

Combine it with ${!v}, which reads the variable whose name is in v, and you have a settings dump:

for v in "${!APP_@}"; do
  echo "$v=${!v}"
done

The names come back sorted, so the output is stable from run to run. I find this nice at the start of a script that runs in a container, where all the configuration comes in as environment variables.

Be careful where that output goes. If one of the variables is APP_PASSWORD or APP_TOKEN, the loop happily prints it into your logs. Filter those out, or print only the names. ${!APP_*} works too; the difference is the same as between $@ and $* once you quote it, so in a loop use the @ form.

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/ set -e All Bash tips (52) All topics

Link