Unix Shell Script Conditional Statements

April 15, 2007 by Mark Marucot · Leave a Comment 

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

Unix Shell Script Variables

April 15, 2007 by Mark Marucot · Leave a Comment 

Variables are use to store information. The syntax of declaring variables is shown below:

CODE:
  1. VAR=value

Note: There must be no spaces between the variable and the value. VAR=value will work but VAR=value will not. The reason is when the shell sees that the “=”, it assumes that it’s a variable assignment. If there is spaces before and after the “=”, it interpreted VAR as a command with two arguments “=” and “value”.

CODE:
  1. #!/bin/sh
  2. MESSAGE=“Hello Unix”
  3. echo $MESSAGE

Read more