Wednesday, December 29, 2010

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

Shell,Basics,Linux,Unixart,MacOSX,OSR5,BSD

2010/03/29

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.

Comments: Click Here.

Want to showcase your product to our audience? Check our advertising options.



Many of the products and books I review are things I purchased for my own use. Some were given to me specifically for the purpose of reviewing them.

I resell or can earn commissions from the sale of some of these items. Links within these pages may be affiliate links that pay me for referring you to them. That's mostly insignificant amounts of money; whenever it is not I have made my relationship plain. If you have any question, please do feel free to contact me.


Source: http://feedproxy.google.com/~r/aplawrence/DOLL/~3/BE3LMajhF60/leading-colon.html

iphone Lindsay Lohan maksim chmerkovskiy colt brennan accident cell phone

No comments:

Post a Comment