r/bash • u/ClickOk5811 • 2h ago
${v:-x} vs ${v-x}: the colon decides whether “empty” counts as unset (tested table)
One character, the colon, changes how Bash treats a variable that’s set but empty. Here are the four basic forms against three states, from a real run on Bash 5.2.21:
for state in unset empty set; do
case $state in
unset) unset v ;;
empty) v="" ;;
set) v="val" ;;
esac
printf '%-7s %-10s %-10s %-10s %-10s\n' "$state" \
"[${v:-D}]" "[${v-D}]" "[${v:+A}]" "[${v+A}]"
doneOutput:
state ${v:-D} ${v-D} ${v:+A} ${v+A}
unset [D] [D] [] []
empty [D] [] [] [A]
set [val] [val] [A] [A]How to read it:
- With the colon (
:-,:+), “unset” and “empty” are treated the same: both count as “no value”. - Without the colon (
-,+), only a truly unset variable counts. An empty string is still a value. ${v:-D}gives a default whenvis unset or empty.${v-D}gives the default only whenvis unset.${v:+A}expands toAonly whenvis set and non-empty.${v+A}expands toAwhenevervis set, even to an empty string.
The error forms follow the same rule:
bash
( unset v; : "${v:?v is unset or empty}" ) # exit 1
( v=""; : "${v:?v is unset or empty}" ) # exit 1
( v=""; : "${v?v is unset}" ) # exit 0
( unset v; : "${v?v is unset}" ) # exit 1So ${v:?msg} aborts on empty as well, while ${v?msg} only aborts on unset. In a script, that aborts the shell (the subshells above just let me show each exit status).
Where it bites:
- A config like
OUT_DIR=""in the environment:${OUT_DIR:-/tmp/out}falls back to the default, while${OUT_DIR-/tmp/out}keeps the empty string, and thenrm -rf "$OUT_DIR"/*would act on/*(dangerous: never run that without a guard). - Flags:
${FORCE+--force}adds the flag whenFORCEis set to anything, even empty.${FORCE:+--force}only when it’s non-empty.
A habit I’d suggest (opinion): use the colon form by default for “give me a default”, and the no-colon form when you really need to tell “unset” from “empty”, and write a comment when you do.
Do you have a rule for which one you use, or do you check with [[ -v v ]] / [[ -n $v ]] instead?