Conditional statements in BASH scripting

You can use if else statements using below syntax

if [ condition ]
then
statements…
elif [ condition ]
statements…
else
statements…
fi

 

Condition can be any of the value.

  1. -eq -> Eqality operator
  2. -ne ->Non-Equality Operator
  3. -gt  -> greater than operator
  4. -ge  -> greater than or equal operator
  5. -lt  -> less than
  6. -le  -> less than or equal to

Examples on if statement

if [ “$mypath” == “/etc” ]
then
          echo “mypath variable is equal to /etc”
else
         echo “mypath variable is not equal to /etc”
fi

If you want to put “then” keyword in the same line, you will have to use semicolon after if condition.

a=11
b=22
if [ “$a” -eq 11 ] && [ “$b” -eq 22 ]
then
           echo “Both conditions are true”
else
          echo “One or both of the conditions are true”
fi

if [ “$a” -eq 11 ] || [ “$b” -eq 23 ]
then
          echo “One or Both of the conditions are true”
else
         echo “Both conditions are false”
fi

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”
fi

cmp command returns 0 when 2 files are same (condition is true).

if cmp f1 f2 &> /dev/null
then
          echo “File f1 and f2 are same.”
else
         echo “File f1 and f2 are not same.”
fi

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 ]
then
         a=1
else
        a=2
fi

Case statements

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” ;;

esac

You may also like...