APLawrence.com -  Resources for Unix and Linux Systems, Bloggers and the self-employed

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

© March 2010 Anthony Lawrence

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

Inexpensive and informative Apple related e-books:

Take Control of High Sierra

Take Control of Numbers

iOS 10: A Take Control Crash Course

Take Control of OS X Server

Take Control of Pages

More Articles by © Anthony Lawrence

Printer Friendly Version

Have you tried Searching this site?

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

Printer Friendly Version

Technology is anything that wasn’t around when you were born. (Alan Kay)

Linux posts

Troubleshooting posts

This post tagged:








Unix/Linux Consultants

Skills Tests

Unix/Linux Book Reviews

My Unix/Linux Troubleshooting Book

This site runs on Linode