Bash if statements

Test

You can check if the condition is true with the command test, here are tables of possible tests.


OperatorDescription
! EXPEXP is false

OperatorDescription
-n STRLength of STR is non-zero
-z STRLength of STR is zero (empty)
STR1 = STR2STR1 is equal to STR2
STR1 != STR2STR1 is different to STR2

OperatorDescription
NUM1 -eq NUM2NUM1 is equal to NUM2
NUM1 -ne NUM2NUM1 is equal to NUM2
NUM1 -gt NUM2NUM1 is greater than NUM2
NUM1 -ge NUM2NUM1 is greater than or equal to NUM2
NUM1 -lt NUM2NUM1 is less than NUM2
NUM1 -le NUM2NUM1 is less than or equal to NUM2

OperatorDescription
-e FILEFILE Exists
-s FILEFILE Exists, and is not empty
-f FILEFILE Exists, and it’s a regular file
-d FILEFILE Exists, and is a directory
-r FILEFILE Exists, and it can be Read (r–)
-w FILEFILE Exists, and it can be Written (-w-)
-x FILEFILE Exists, and it can be eXecuted (–x)

Basic

if [ 2 -eq 2 ]
then
   echo "yes"
fi

Else

if [ "2" = 2 ]
then
   echo "yes"
else
   echo "no"
fi

Else If

if [ 2 -ge 2 ]
then
   echo "yes"
elif [ 2 -lt 2 ]
then
   echo "no"
fi

Boolean Logic

if [ 2 -eq 2 ] && [ 2 -ge 2 ]
then
   echo "yes"
fi
if [ "2" = 2 ] || [ 2 -lt 2 ]
then
   echo "yes"
fi

Case

case $1 in
   2)
   echo "2"
   ;;
   a)
   echo "a"
   ;;
   *)
   echo "error"
   ;;
esac