Mac OS X,  Ubuntu,  Unix

Using a Colon As A Bash Null Operator

I was recently talking with someone that was constructing an If/Then and they wanted a simple echo to match only if a condition was not met. Given their other requirements it seemed a great use for a null operator, which in bash can be a colon (:). This has the equivalent of /dev/null, but with less typing.

One example of populating something with null is if you have a case where you want to create a file where there may or may not be a file already, and you want your new file to be empty (or start empty so you can write lines into it). Here, you could have a line in a script that simply sent null to the file. Here, we’ll use this to create a file called seldon:

: > /temp/seldon

You might expect to see a colon in the above created /temp/seldon file, but you don’t because : was interpreted as null. You could also run it without the colon and end up with the same thing.

> /temp/seldon

If you echo :, you will see a colon echo’d to the screen. This renders the colon unnecessary, but it is just an example, leading up to another where you would need something, as the payload of an If/Then. In the following case, let’s say that we are checking to see if variable $A is 1 and if it isn’t we’ll create an empty file called seldon

if [ "$A" = "1" ];
then
:
else
: > /temp/seldon
fi

To test whether a string hasn’t yet been declared, you can use -n:

if [ -n $a ]

But you can also use the colon to shorten or eliminate the need for certain If/Then blocks entirely. To quote the bash reference (from http://www.gnu.org/software/bash/manual/bashref.html):

When not performing substring expansion, using the form described below, Bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.

This means that in the following, if $A has nothing to expand set to 1, otherwise leave it alone:

${A:=1}

But, if you wanted to do the opposite and say that if it has nothing to expand leave it and if it has something, reset that something to 1:

${A:+1}

There are a bunch of other uses in the link provided for the bash manual as well, but overall, you can cut out a lot of typing using a little old colon…