HeadlinesBriefing favicon HeadlinesBriefing.com

Shell Colon Tricks: Null Command & Parameter Expansion

Hacker News •
×

Filip Roséen discovers the shell colon (:) — a null command that does nothing but evaluates arguments. Dating to the 1971 Thompson shell, it serves as both label and comment marker. The real power emerges when combined with parameter expansion.

Checking required arguments shrinks from four lines to one: `: "${1:?missing argument, aborting.}"`. The :? syntax exits with an error if the variable is unset or empty, printing the diagnostic. Named variables improve clarity: `: "${GREET_NAME:?missing argument, aborting.}"`.

Beyond :?, the colon enables clever idioms: `: "${DATA_DIR:=/var/data}"` sets defaults while discarding the result; `: > error.log` truncates files; `( : < dataset.json ) && echo YES` tests readability; `trap : INT` satisfies trap's command requirement; `set -u; : "$DEPLOY_ENV" "$HOST"` validates variables.

The FAQ explains why the null command is essential: without it, parameter expansion results are executed as commands. Using `: ${VAR:=default}` avoids typos by mentioning the variable once, unlike `VAR=${VAR:-default}` which risks duplication errors.