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
| Operator | Description |
|---|---|
-f | Checks if a file exists and is a regular file. |
-d | Checks if a directory exists. |
-z STRING | Checks if STRING is empty (zero length). |
== | String equality. |
-gt | Greater than (for integers). |
-eq | Equal 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.