Sunday, 4 September 2011

Various syntaxes of if statement in shell

The basic rules of conditions

When you start writing and using your own conditions, there are some rules you should know to prevent getting errors that are hard to trace. Here follow three important ones:
  1. Always keep spaces between the brackets and the actual check/comparison. The following won't work:
    if [$foo -ge 3]; then
    Bash will complain about a "missing `]'".
  2. Always terminate the line before putting a new keyword like "then". The words if, then, else, elif and fi are shell keywords, meaning that they cannot share the same line. Put a ";" between the previous statement and the keyword or place the keyword on the start of a new line. Bash will throw errors like "syntax error near unexpected token `fi'" if you don't.
  3. It is a good habit to quote string variables if you use them in conditions, because otherwise they are likely to give trouble if they contain
    spaces and/or newlines. By quoting I mean:
    if [ "$stringvar" == "tux" ]; then
    There are a few cases in which you should not
    quote, but they are rare. You will see one of them further on in the tutorial.
Also, there are two things that may be useful to know:
  1. You can invert a condition by putting an "!" in front of it. Example:
    if [ ! -f regularfile ]; then
    Be sure to place the "!" inside the brackets!
  2. You can combine conditions by using certain operators. For the single-bracket syntax that we've been using so far, you can use "-a" for and and "-o" for or. Example:
    if [ $foo -ge 3 -a $foo -lt 10 ]; then
    The above condition will return true if $foo contains an integer greater than or equal to 3 and Less Than 10. You can read more about these combining expressions at the respective condition syntaxes.
And, one more basic thing: don't forget that conditions can also be used in other statements, like while and until. It is outside the scope of this tutorial to explain those, but you can read about them at the Bash Guide for Beginners.
Anyway, I've only shown you conditions between single brackets so far. There are more syntaxes, however, as you will read in the next section.
To know more :

No comments:

Post a Comment

Tweets by @sriramperumalla