Unix Shell Script Conditional Statements

April 15, 2007 by Mark Marucot 

Conditional statements are use to perform specific action/s based on a given conditions
if Statement

The if statement performs specific statement/s if the condition is met otherwise the set of statements is skipped.

CODE:
  1. if [ condition ]
  2. then
  3. # if-code
  4. fi

Wrong

CODE:
  1. if [$foo = "bar" ]

Correct

CODE:
  1. if [ "$foo" = "bar" ]

Note: Bracket ([) is actually a program which means it is required to place spaces in between the condition because it reads the next group of words or letters as arguments or program parameters. Syntax should be if [ space <var1> space <operator> space <var2> space ]

if .. else Statement

The if .. else statement performs specific statement/s if the condition is met otherwise the another statement/s is performed.

CODE:
  1. if [ condition ]
  2. then
  3. # if-code
  4. else
  5. # else-code
  6. fi

if .. else if .. else Statement

The if .. else if .. else statement performs specific statement/s if there are three or more conditions.

CODE:
  1. if [ condition1 ]; then
  2. # if-code
  3. elif [ condition2 ]; then
  4. # if-code
  5. else
  6. # else-code
  7. fi

Related Posts

Comments

Feel free to leave a comment...
and oh, if you want a pic to show with your comment, go get a gravatar!