if..else statement in Bash

This article will introduce how to use if..else statement in Bash.

1. Syntax

It can be used with if, if-else, if-elif-else patterns, just like in other languages.

if [ expression ]
then
    statement
elif [ expression ]
then
    statement
else
    statement
fi

2. Example: if-else

In this example, $a = $b will be True when a and b are the same, and False when they are different.

#!/bin/bash

a=10
b=20

if [ $a = $b ]
then
    echo "a is equal to b"
else
    echo "a is not equal to b"
fi

Output:

$ bash example.sh
a is not equal to b

3. Example: if-elif-else

In this example, [ $a -lt $b ] means a < b.

#!/bin/bash

a=10
b=20

if [ $a = $b ]
then
    echo "a is equal to b"
elif [ $a -lt $b ]
then
    echo "a is less than b"
else
    echo "a is not equal to b"
fi

Output:

$ bash example.sh
a is less than b

4. Example: if not..

To apply not to [ expression ], you can add a ! to the expression, either ! [ expression ] or [ ! expression ].

#!/bin/bash

a=10
b=20

if ! [ $a = $b ]
then
    echo "a is not equal to b"
else
    echo "a is equal to b"
fi

Output:

a is not equal to b

5. OR and AND operators

You can apply either an OR or an AND operator to two conditions.

The AND operator can be used in the form [ expression ] && [ expression ].

#!/bin/bash

a=10
b=20

if [ $a = 10 ] && [ $b = 20 ]
then
    echo "a is 10 and b is 20"
fi

Output:

a is 10 and b is 20

And, the OR operator can be used in the form like [ expression ] || [ expression ].

#!/bin/bash

a=10
b=20

if [ $a = 10 ] || [ $b = 10 ]
then
    echo "a is 10 or b is 10"
fi

Output:

a is 10 or b is 10

6. Test operator

Test operators are operators that compare two variables or check the type or permission of a file.

You can use test operators with if [ statement ].

There are some test operators as follows.

Operator Description Value
! EXPRESSION The EXPRESSION is false.
-n STRING The length of STRING is greater than zero.
-z STRING The lengh of STRING is zero (ie it is empty).
STRING1 = STRING2 STRING1 is equal to STRING2
STRING1 != STRING2 STRING1 is not equal to STRING2
INTEGER1 -eq INTEGER2 INTEGER1 is numerically equal to INTEGER2
INTEGER1 -gt INTEGER2 INTEGER1 is numerically greater than INTEGER2
INTEGER1 -lt INTEGER2 INTEGER1 is numerically less than INTEGER2
-d FILE FILE exists and is a directory.
-e FILE FILE exists.
-r FILE FILE exists and the read permission is granted.
-s FILE FILE exists and it's size is greater than zero (ie. it is not empty).
-w FILE FILE exists and the write permission is granted.
-x FILE FILE exists and the execute permission is granted.
codechachaCopyright ©2019 codechacha