Conditional statements in BASH scripting
You can use if else statements using below syntax
if [ condition ]
elif [ condition ]
Condition can be any of the value.
- -eq -> Eqality operator
- -ne ->Non-Equality Operator
- -gt -> greater than operator
- -ge -> greater than or equal operator
- -lt -> less than
- -le -> less than or equal to
Examples on if statement
if [ “$mypath” == “/etc” ]
echo “mypath variable is equal to /etc”
echo “mypath variable is not equal to /etc”
If you want to put “then” keyword in the same line, you will have to use semicolon after if condition.
if [ “$a” -eq 11 ] && [ “$b” -eq 22 ]
echo “Both conditions are true”
echo “One or both of the conditions are true”
if [ “$a” -eq 11 ] || [ “$b” -eq 23 ]
echo “One or Both of the conditions are true”
echo “Both conditions are false”
When grep command finds at least one pattern in a file, it returns 0 (condition is true)
if grep -q pattern myfile
then echo “pattern found in myfile”
cmp command returns 0 when 2 files are same (condition is true).
if cmp f1 f2 &> /dev/null
echo “File f1 and f2 are same.”
echo “File f1 and f2 are not same.”
Conditional operator in Linux
? operator works in the same as in Java language.
Syntax of ? operator is given below.
var = <condition> ? <trueValue>:<falseValue>
If the condition is true, trueValue is assigned to variable “var”.
If the condition is false, falseValue is assigned to variable “var”.
For example –
below statement is same as the if else block that follows.
(( a = b > 3 ? 1:2 ))
if [ b -gt 3 ]
Case statements are similar to switch …case statements in C language. Here is the syntax. Note that we need to use ;; to mark the end of case block.
case “$switch” in
1) echo “Case 1” ;;
2) echo “Case 2” ;;