Conditional statements
Conditional statements help you to execute parts of a shell script only if
certain conditions hold. Below, we give the syntax and examples for three
common variants of if
statements as well as the case
statement which acts
like switch statements in other languages.
if ... fi
General syntax:
if [ expression ]
then
Statement(s) to be executed if expression is true
fi
Here, expression
often takes the form of comparing strings using operators ==
or !=
or comparing numbers using operators -eq
(equal), -ne
(not equal), -lt
(less than), -gt
(greater than), or -ge
(greater than or equal to).
However, there are other conditional expressions, many related to files (for example -e test.txt
returns true if the file test.txt
exists). For a full listing, see this manual page.
Example:
#!/bin/bash
if [ $1 == $2 ]
then
echo "$1 is equal to $2"
fi
This is the result of a sample run.
bash ./test.sh
is equal to
bash ./test.sh 1 2
bash ./test.sh 12 12
12 is equal to 12
if ... else ... fi
General syntax:
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:
#!/bin/bash
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.
bash ./test.sh
is equal to
bash ./test.sh 1 2
1 is not equal to 2
bash ./test.sh 12 12
12 is equal to 12
if ... elif ... else ... fi
General syntax:
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:
#!/bin/bash
if [ $1 -eq $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.
bash ./test.sh
is equal to
bash ./test.sh 1 2
1 is less than 2
bash ./test.sh 12 2
12 is greater than 2
bash ./test.sh 12 12
12 is equal to 12
case ... esac
General syntax:
case word in
patterns ) commands ;;
esac
Example:
#!/bin/bash
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.
bash 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.
bash test.sh
Enter a number between 1 and 3 inclusive > 3
You entered three.
bash test.sh
Enter a number between 1 and 3 inclusive > 4
You did not enter a number between 1 and 3.