views:

198

answers:

3
+5  Q: 

Shell script test

I'm tring to update a bash script written by someone else and I've come accross a line I'm not sure about.

Can anyone tell me what the following check does:

if [ :$RESULT != :0,0 ]

I assume it's checking for some value in $RESULT, possibly with a substring?

Any help appreciated!

+4  A: 

I think the : is a common trick people use in case the variable is empty.

If it's empty, then the shell would have this:

if [  != 0,0 ]

which would be a syntax error. Putting the : in front means that if the variable is empty the shell has this:

if [ : != :0,0 ]

which is not a syntax error and would (correctly) report false.

Rory
+11  A: 

The command [ is just an alias of the command test, the closing square bracket just being sytax sugar (the command [ ignores the last argument if it's a closing bracket), so the line actually reads

if test :$RESULT != :0,0

It compares if the string :$RESULT equals to the string :0,0. The colon is prepended for the case that the variable $RESULT is empty. The line would look like the following if the colon was omitted and $RESULT was an empty string:

if test  != 0,0

This would lead to an error, since test expects an argument before !=. An alternative would be to use quotes to indicate that there is an argument, which is an empty string:

if test "$RESULT" != 0,0
# Will become
if test "" != 0,0

The variation you posted is more portable, though.

soulmerge
Try `man bash` and search for the builtin command `test` for further info
soulmerge
Okay, I follow that, thanks! So is it actually comparing to the string "0,0"? I only ask as the variable result would never have that value!I wondered if the 0,0 does something else. A blank string perhaps?
No, `0,0` is a string and the operator `!=` compares strings, so it checks if `$RESULT` is the string `0,0`. Try `man test`.
soulmerge
Just done some small tests and you are indeed absolutely right. Thanks!
+1  A: 

Sometimes you'll see an x used in the way that the colon is used in your example.

The preferred way to do this type of test in Bash is to use the double square bracket:

if [[ $RESULT != 0,0 ]]

The double bracket form allows more flexibility, improved readability, reduced need for escaping and quoting and a few more features. See this page for more information.

If you want to test numeric values, instead of strings or files, use the double parentheses:

if (( 3 + 4 > 6 ))
Dennis Williamson