RC RANDOM CHAOS

The shell's do-nothing colon is a scripting power tool in disguise

· via Hacker News

Original source

A shell colon does nothing. Use it anyway

Hacker News →

The humble : null-command in POSIX shells evaluates its arguments and throws away the result, doing nothing on its own. That uselessness is exactly what makes it handy: paired with parameter expansion, it collapses common boilerplate into a single line. Instead of writing a four-line if-block to reject a missing argument, you can write : "${1:?missing argument, aborting.}", which prints a diagnostic to stderr and exits non-zero when the value is unset or empty. Naming the variable makes the error message even clearer, since the shell reports the variable name in the failure.

The colon dates back to the 1971 Thompson shell, where it served as both a label and Unix’s first comment marker. Beyond argument checks, it enables a grab-bag of terse idioms: assigning defaults with : "${DATA_DIR:=/var/data}", truncating files with : > error.log, probing whether a file is readable or writable via redirection tests, and satisfying constructs like trap and empty if/else branches that syntactically require a command. Prefixing an expansion with : matters because without a command in front, the shell tries to execute the expansion’s result as a program.

The practical appeal is fewer keystrokes and fewer chances to typo. Writing : "${DATA_DIR:=/var/data}" mentions the variable name once, versus the two references in DATA_DIR="${DATA_DIR:-/var/data}", halving the surface for a mismatched-name bug. It is a small, old feature, but one that repays the few minutes it takes to learn.

Read the full article

Continue reading at Hacker News →

This is an AI-generated summary. Read the original for the full story.