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.
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:
test.sh
123456
#!/bin/bashif[$1==$2]thenecho"$1 is equal to $2"fi
#!/bin/bashif[$1-eq$2]thenecho"$1 is equal to $2"elif[$1-gt$2]thenecho"$1 is greater than $2"elif[$1-lt$2]thenecho"$1 is less than $2"elseecho"None of the condition met"fi
This is the result of a sample run.
input
1
bash./test.sh
output
1
is equal to
input
1
bash./test.sh12
output
1
1 is less than 2
input
1
bash./test.sh122
output
1
12 is greater than 2
input
1
bash./test.sh1212
output
1
12 is equal to 12
case ... esac
General syntax:
123
casewordinpatterns)commands;;esac
Example:
test.sh
1 2 3 4 5 6 7 8 9101112
#!/bin/bashread-p"Enter a number between 1 and 3 inclusive > "character
case$characterin1)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.
input
1
bashtest.sh
output
12
Enter a number between 1 and 3 inclusive > 1You entered one.
input
1
bashtest.sh
output
12
Enter a number between 1 and 3 inclusive > 2You entered two.
input
1
bashtest.sh
output
12
Enter a number between 1 and 3 inclusive > 3You entered three.
input
1
bashtest.sh
output
12
Enter a number between 1 and 3 inclusive > 4You did not enter a number between 1 and 3.