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: [[ -v name ]] tells bash whether a variable is set at all

Bash
~/tips/tip-bash-test-v-variable-set

[[ -v b ]] && echo set || echo unset # set

Tell an unset variable apart from one that is set to an empty string.

[ -z "$VAR" ] cannot tell the difference between a variable that was never set and one set to an empty string. Sometimes that difference is the whole point.

-v checks whether the name exists, whatever its value:

unset a; b=
[[ -v a ]] && echo set || echo unset   # unset
[[ -v b ]] && echo set || echo unset   # set

That makes it handy for flags in the environment. DRY_RUN= ./deploy.sh then counts as switched on, even without a value:

if [[ -v DRY_RUN ]]; then
  echo "dry run, nothing will change"
fi

It also works with set -u switched on, which makes $a on an unset variable a fatal error, but [[ -v a ]] is fine.

Note that you give the name, not the value: -v DRY_RUN, without a dollar sign. Writing [[ -v $DRY_RUN ]] tests a variable whose name is whatever DRY_RUN contains, which is almost never what you meant. It also checks array elements and keys, like [[ -v ports[web] ]] on an associative array. I like it, but it needs bash 4.2 or newer, so the old bash 3.2 on macOS does not have it.

Further reading: Bash manual: Bash Conditional Expressions

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