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: declare -p shows exactly what is inside a bash variable or array

Bash
~/tips/tip-bash-declare-p-inspect-variable

declare -p apps

Prints the type and exact quoted value of a bash variable, array or function.

echo "$var" is the debugging tool most of us reach for, and it hides the interesting bits. A trailing space, an empty element or an array that is really a plain string all look the same once echo is done with them. declare -p shows the real thing.

Give it the name of a variable (without the $) and it prints the attributes and the value, quoted, the way bash itself sees it:

apps=(jellyfin "home assistant" "")
declare -p apps
# declare -a apps=([0]="jellyfin" [1]="home assistant" [2]="")

declare -A port=([sonarr]=8989)
declare -p port
# declare -A port=([sonarr]="8989" )

Right away you see three elements, where echo "${apps[@]}" would have shown something that looks like three or four words. The letters after declare tell you the type: -a for an indexed array, -A for an associative one, -x for exported, -i for integer and -- for a plain variable. That last one is how you catch an array that never became an array.

You can pass several names at once, declare -p apps port, and declare -f name prints the definition of a function, which is useful when you’ve lost track of which version of a helper is loaded in your shell.

The caveat: it shows the variable as it is visible right where you call it. Inside a function with a local of the same name, you see the local one. And for a name that doesn’t exist, it prints a “not found” error and returns 1, so in a script with set -e a debug line like this can stop the run. I’d add || true to it there.

Further reading: bash(1) manual page

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