Tuesday, May 6, 2008

bash quicksand 2: Quotes needed in string tests

This is part 2 of the bash quicksand series. Part 1 is about whitespaces
in variable assignment
. When you write bash shell scripts, you want to avoid these innocent-looking mistakes. We all fall into these traps at some point, especially when we first write bash scripts.

You define a bash variable, say $somevar. Later, you need to test if it is equal to some string, say "linux".

1  #!/bin/bash
...
5 if [ $somevar == "linux"]
6 then ...
9 fi
...
25 exit 0


Depending on the value of $somevar at the time of the test, you can see some puzzling errors:

  • If $somevar is null (""), then you will see this error:
    ./myscript.sh: line 5: [: =: unary operator expected

  • If $somevar has embedded spaces, e.g., "tux is great", you will see this error:
    ./myscript.sh: line 5: [: too many arguments



Now, you know this trap, don't fall into it.

A good defence is to always enclose the bash variable in quotes:
if [ "$somevar" == "linux"]
then ...
fi

No comments: