Friday, August 12, 2016

Arcane Bourne shell behavior. The colon (:)

I finally learned the purpose of starting a command with the colon utility (:) in bourne shell. It expands any arguments, then exits 0. This is handy for hiding pointless error messages resulting from variable substitution. Consider the following example.

$ ${D:=foo}
foo: not found
$ echo $D
foo

The example above sets variable D to "foo" if it is unset or null. It works fine, but causes the annoying error 'foo: not found'. We can suppress that message with the colon.

$ unset D
$ : ${D:=foo}
$ echo $D

foo

Much prettier!

Also see:
Parameter Expansion (and explanation of the colon utility at the bottom of the page)