Back to course

Conditional Logic: if, elif, else Statements

Termux Masterclass: From Zero to Linux Power User on Android

29. Conditional Logic: if, elif, else Statements

Conditional statements allow scripts to make decisions based on whether a condition is true or false. This is done using the test command, often represented by square brackets ([ ]).

The if/then/else Structure

bash if [ condition ]; then # Commands if condition is true elif [ condition2 ]; then # Commands if condition 2 is true else # Commands if all conditions are false fi # 'if' reversed, denotes the end of the block

Common Test Operators

OperatorDescription
-fChecks if a file exists and is a regular file.
-dChecks if a directory exists.
-z STRINGChecks if STRING is empty (zero length).
==String equality.
-gtGreater than (for integers).
-eqEqual to (for integers).

Example: Checking File Existence

Let's check if backup.tar.gz exists before proceeding.

bash #!/bin/bash

FILENAME="backup.tar.gz"

if [ -f "$FILENAME" ]; then echo "$FILENAME exists. Initiating upload..." # Add upload command here else echo "Error: $FILENAME not found. Aborting." exit 1 fi

Note: Spaces are mandatory around the brackets ([ condition ]) and around the test operators.