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.
-
if [ condition ]
-
then
-
# if-code
-
fi
Wrong
-
if [$foo = "bar" ]
Correct
-
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.
-
if [ condition ]
-
then
-
# if-code
-
else
-
# else-code
-
fi
if .. else if .. else Statement
The if .. else if .. else statement performs specific statement/s if there are three or more conditions.
-
if [ condition1 ]; then
-
# if-code
-
elif [ condition2 ]; then
-
# if-code
-
else
-
# else-code
-
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:
-
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”.
-
#!/bin/sh
-
MESSAGE=“Hello Unix”
-
echo $MESSAGE



