How to Use Bash if loops (if then, if else then, if then elif then else)
Simple shell scripts represent a collection of commands which are executed from beginning to end. Conditional structures allow users to incorporate decision making into shell scripts so that certain portions of the script are executed only when certain conditions are met.
if/then statement
The simplest of the conditional structures in Bash is the if/then construct, which has the following syntax.
if [CONDITION]; then
[STATEMENT]
...
[STATEMENT]
fi
With this construct, if a given condition is met, one or more actions are taken. If the given condition is not met, then no action is taken. The numeric, string, and file tests previously demonstrated are frequently utilized for testing the conditions in if/then statements. The following code section demonstrates the use of an if/then statement to start the psacct service if it is not active.
systemctl is-active psacct > /dev/null 2>&1
if [ $? -ne 0 ]; then
systemctl start psacct
fi
if/then/else statement
The if/then conditional structure can be further expanded so that different sets of actions can be taken depending on whether a condition is met. This is accomplished with the if/then/else conditional construct.
if [CONDITION]; then
[STATEMENT]
...
[STATEMENT]
else
[STATEMENT]
...
[STATEMENT]
fi
The following code section demonstrates the use of an if/then/else statement to start the psacct service if it is not active and to stop it if it is active.
systemctl is-active psacct > /dev/null 2>&1
if [ $? -ne 0 ]; then
systemctl start psacct
else
systemctl stop psacct
fi
if/then/elif/then/else statement
Lastly, the if/then/else conditional structure can be further expanded to test more than one condition, executing a different set of actions when a condition is met. The construct for this is shown in the following example. In this conditional structure, Bash will test the conditions in the order presented. Upon finding a condition that is true, Bash will execute the actions associated with the condition and then skip the remainder of the conditional structure. If none of the conditions are true, then Bash will execute the actions enumerated in the else clause.
if [CONDITION]; then
[STATEMENT]
...
[STATEMENT]
elif [CONDITION]; then
[STATEMENT]
...
[STATEMENT]
else
[STATEMENT]
...
[STATEMENT]
fi
The following code section demonstrates the use of an if/then/elif/then/else statement to run the mysql client if the mariadb service is active, run the psql client if the postgresql service is active, or run the sqlite3 client if both the mariadb and postgresql services are not active.
systemctl is-active mariadb > /dev/null 2>&1
MARIADB_ACTIVE=$?
systemctl is-active postgresql > /dev/null 2>&1
POSTGRESQL_ACTIVE=$?
if [ "$MARIADB_ACTIVE" -eq 0 ]; then
mysql
elif [ "$POSTGRESQL_ACTIVE" -eq 0 ]; then
psql
else
sqlite3
fi