r/bash • • 2h ago

${v:-x} vs ${v-x}: the colon decides whether “empty” counts as unset (tested table)

1 Upvotes

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}]"
done

Output:

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 when v is unset or empty. ${v-D} gives the default only when v is unset.
  • ${v:+A} expands to A only when v is set and non-empty. ${v+A} expands to A whenever v is 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 1

So ${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 then rm -rf "$OUT_DIR"/* would act on /* (dangerous: never run that without a guard).
  • Flags: ${FORCE+--force} adds the flag when FORCE is 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?


r/bash • • 13h ago

solved I got tired of Claude Code trying to read .env and dump process.env, so I built an open-source PreToolUse hook & stream redactor (zero deps)

Thumbnail reddit.com
0 Upvotes