Linux if statement with examples

In this tutorial, we are going to see Linux if statement with examples.

If statements allow us to make decisions in our Bash scripts. They allow us to decide whether or not to run a piece of code based upon conditions that we may set.

If Statement Syntax:

if condition then statements fi

The basic rules of if statement conditions:

1. Always keep spaces between the brackets and the actual check/comparison.
2. Always terminate the line before putting a new keyword like “then”.

Linux if examples:

1. Check the mysql directory exists or not in /var/log/ directory using Linux shell script.

#!/bin/bash echo "This scripts checks the existence of the mysql directory." echo "Checking..." if [ -d /var/log/mysql/ ] then echo "/var/log/mysql exists." fi

Output:

2. Check the pg_hba.conf exists or not using Linux shell script.

#!/bin/bash echo "This scripts checks the existence of the postgresql pg_hba.conf." if [ -f /etc/postgresql/12/main/pg_hba.conf ] then echo "/etc/postgresql/12/main/pg_hba.conf exists." fi

Output:

Linux if statement with examples

3. Compare two values.

#!/bin/bash read a read b if [ $a -gt $b ] then echo a is greater than b fi

Output: