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.
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-lineifstatements 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.logor: > error.log > access.logleveraging output redirection. - Checking file permissions:
( : < dataset.json ) && echo YESto test readability or( : >> result.json ) && echo YESfor writability. - Providing a command for
trap:trap : INTto effectively ignore signals. - Validating multiple variables: When
set -uis active,: "$DEPLOY_ENV" "$HOST"checks if both variables are set. - Acting as a no-op placeholder: In
if/elseblocks where a command is syntactically required but no action is desired.
- Setting default values:
- 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 toVAR="${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.