HN
Today

A shell colon does nothing. Use it anyway

This article uncovers the surprising utility of the seemingly innocuous colon in shell scripting, revealing how this ancient command can drastically simplify and improve code conciseness. It demonstrates clever parameter expansion tricks and the null command's role in tasks like argument validation and variable defaults. Shell enthusiasts on HN appreciate these deep dives into Unix arcana, which offer powerful, lesser-known techniques to write more robust and efficient scripts.

14
Score
3
Comments
#1
Highest Rank
16h
on Front Page
First Seen
Jul 26, 5:00 AM
Last Seen
Jul 26, 8:00 PM
Rank Over Time
1121112425581618202628

The Lowdown

The author shares a profound discovery: the immense utility of the humble colon (:) in shell scripting, a trick that blew their mind despite years of experience. This article delves into how the null command and parameter expansion can streamline script logic, reduce boilerplate, and enhance script reliability.

  • Mandatory Argument Checking: The article highlights how :${1:?message} can replace multi-line if statements to validate required arguments, printing a diagnostic message to stderr and exiting if the variable is unset or empty.
  • The Null Command (:): It's introduced as a builtin command that does nothing but evaluate its arguments and discard the result. Dating back to the 1971 Thompson shell, it also served as a label and the first comment marker.
  • Advanced Colon Applications: Beyond argument checks, the colon can be used for:
    • Setting default values: : "${DATA_DIR:=/var/data}" to assign a default if a variable is unset or null.
    • Truncating files: : > error.log or : > error.log > access.log leveraging output redirection.
    • Checking file permissions: ( : < dataset.json ) && echo YES to test readability or ( : >> result.json ) && echo YES for writability.
    • Providing a command for trap: trap : INT to effectively ignore signals.
    • Validating multiple variables: When set -u is active, : "$DEPLOY_ENV" "$HOST" checks if both variables are set.
    • Acting as a no-op placeholder: In if/else blocks where a command is syntactically required but no action is desired.
  • Clarifications: An FAQ section explains that the null command is crucial for parameter expansions like ${VAR:=default} because without it, the shell would try to execute the expanded result as a command. It also notes that using := with : can reduce typos compared to VAR="${VAR:-default}", as the variable name is only typed once.

Ultimately, the article champions the study of the null command and parameter expansion, presenting them as invaluable tools for writing concise, resilient, and effective shell scripts, helping scripters avoid cold coffee and repetitive code.