Colon command in shell scripts
Redowan Delowar
December 23, 2022
The colon : command is a shell utility that represents a truthy value. It can be thought
of as an alias for the built-in true command. You can test it by opening a shell script
and typing a colon on the command line, like this:
If you then inspect the exit code by typing $? on the command line, you'll see a 0
there, which is exactly what you'd see if you had used the true command.
The output will be:
I find the colon command useful when running a shell script with the -x flag, which prints
out the commands being executed by the interpreter. For example, consider the following
script:
Running this script with bash -x script.sh will print the following lines:
Notice that the above script prints out each command first (denoted by a preceding + sign)
and then its respective output. However, the echo "section..." commands in this script are
only used for debugging purposes, to enhance the readability of the output by providing
separation between different sections. Therefore, repeating these commands and their outputs
can be a little redundant. You can use the colon command to eliminate this repetition, as
follows:
Running this script with the -x flag will produce the following output:
If you look closely, you'll see that the debug commands and their outputs are no longer
getting repeated.
Further reading
- [Why I use the colon command by @anthonywritescode]
[why i use the colon command by @anthonywritescode]:
https://www.youtube.com/watch?v=onkNf1AKSgg
Discussion in the ATmosphere