What does a leading colon (:) mean in a script?

Bash and sh both use colons (":") in more than one context. You'll see it used as a separator ($PATH, for example), as a modifier (${n:="foo"}) and as a null operator ("while :").

You'll also see the null operator usage in "if-then" sections:

if [ "$T1" = "$T2" ]
      echo "Nope"

In that case, the ":" is just a "do-nothing" place holder.

The use that probably causes the most head-scratching is when it appears at the beginning of a line:

: > somefile

What does that mean? It simply clears out "somefile" or creates an empty "somefile" if it didn't exist already. In most shells, you wouldn't need the ":" at all - a '> somefile' would work just as well. But that wouldn't work in Csh - you'd get "Invalid null command".

You could 'cat /dev/null > somefile' but that's a lot of typing and is very Unix specific. You could 'echo -n > somefile' on many systems, but on a few you might need 'echo "\c"' instead. Using ': > somefile' is short, not Unix specific and avoids variances in 'echo'.

Another place you might see it is with conditional variable setting. For example, say we want to set xx to "foo" but only if it isn't already set. We can use use '${xx:="foo"}' as a shorthand way to avoid "if" or "case" blocks, but that has a side effect:

-bash: foo: command not found

You could redirect errout to stop that complaint, but what if 'foo' were a real command? It would be executed, and that might not be what you want. You can avoid that by the leading ":" again:

: ${xx:="foo"}

So that's why those leading colons are often found in shell scripts.

Got something to add? Send me email.

(OLDER) <- More Stuff -> (NEWER)    (NEWEST)   

Printer Friendly Version

-> -> Use of null (:) operator in shell scripts

Increase ad revenue 50-250% with Ezoic

More Articles by

Find me on Google+

© Anthony Lawrence

Kerio Samepage

Have you tried Searching this site?

Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us