Linux if else statement with examples

In this article, we will see Linux if else statement with examples.

If else 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 condition then statements else 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/post] then echo "/var/log/mysql exists." else echo "folder not exists" fi

Output:

Linux if else statement with examples

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." else echo "configuration file not exists" fi

Output:

3. Compare two values with Linux if else.

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

Output: