Skip to content

4. Conditional statements

if...fi/if...else...fi/if...elif...else...fi

if...fi

1
2
3
4
if [ expression ]
then
   Statement(s) to be executed if expression is true
fi

Example:

1
2
3
4
5
6
#!/bin/sh

if [ $1 == $2 ]
then
   echo "$1 is equal to $2"
fi

This is the result of a sample run.

1
2
3
4
5
sh ./sample.sh
 is equal to
$ sh ./test.sh 1 2
$ sh ./test.sh 12 12
12 is equal to 12

if...else...fi

1
2
3
4
5
6
if [ expression ]
then
   Statement(s) to be executed if expression is true
else
   Statement(s) to be executed if expression is not true
fi

Example:

1
2
3
4
5
6
7
8
#!/bin/sh

if [ $1 == $2 ]
then
   echo "$1 is equal to $2"
else
   echo "$1 is not equal to $2"
fi

This is the result of a sample run.

1
2
3
4
5
6
7
8
$ sh ./test.sh
 is equal to

$ sh ./test.sh 1 2
1 is not equal to 2

$ sh ./test.sh 12 12
12 is equal to 12

if...elif...else...fi

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
if [ expression 1 ]
then
   Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
   Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
   Statement(s) to be executed if expression 3 is true
else
   Statement(s) to be executed if no expression is true
fi

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/bin/sh

if [ $1 == $2 ]
then
   echo "$1 is equal to $2"
elif [ $1 -gt $2 ]
then
   echo "$1 is greater than $2"
elif [ $1 -lt $2 ]
then
   echo "$1 is less than $2"
else
   echo "None of the condition met"
fi

This is the result of a sample run.

1
2
3
4
5
6
7
8
9
#!/bin/sh
sh ./test.sh
 is equal to
$ sh ./test.sh 1 2
1 is less than 2
$ sh ./test.sh 12 2
12 is greater than 2
$ sh ./test.sh 12 12
12 is equal to 12

case...esac

1
2
3
case word in
    patterns ) commands ;;
esac

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/bin/sh

read -p "Enter a number between 1 and 3 inclusive > " character
case $character in
    1 ) echo "You entered one."
        ;;
    2 ) echo "You entered two."
        ;;
    3 ) echo "You entered three."
        ;;
    * ) echo "You did not enter a number between 1 and 3."
esac

This is the result of a sample run.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
$ sh test.sh
Enter a number between 1 and 3 inclusive > 1
You entered one.

$ bash test.sh
Enter a number between 1 and 3 inclusive > 2
You entered two.

$sh test.sh
Enter a number between 1 and 3 inclusive > 3
You entered three.

$sh test.sh
Enter a number between 1 and 3 inclusive > 4
You did not enter a number between 1 and 3.