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

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


Some material is very old and may be incorrect today

© 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" ]
then
      :
else
      echo "Nope"
fi           
 

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:

${xx:="foo"}
-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.


If you found something useful today, please consider a small donation.



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:

Sierra: A Take Control Crash Course

Photos for Mac: A Take Control Crash Course

El Capitan: A Take Control Crash Course

Take Control of Preview

Take Control of iCloud, Fifth Edition





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





May you live long enough to regret your opinions - (Tony Lawrence)




Linux posts

Troubleshooting posts


This post tagged:

BSD

Basics

Linux

SCO_OSR5

Scripting

Shell

Unixart



Unix/Linux Consultants

Skills Tests

Unix/Linux Book Reviews

My Unix/Linux Troubleshooting Book

This site runs on Linode