if Statement
The if statement is a fundamental control structure in shell scripting that allows conditional execution of commands based on the success or failure of test conditions.
Syntax
then
commands
fi
# Alternative single-line syntax
if [ condition ]; then commands; fi
Description
The if statement evaluates a condition and executes commands based on whether the condition is true (exit status 0) or false (non-zero exit status).
Key features:
- Conditional command execution
- Support for else and elif clauses
- Multiple test operators and conditions
- Nested if statements
- Integration with command exit codes
Common Test Operators
| Operator | Description | Example |
|---|---|---|
-eq |
Equal to (numeric) | [ $a -eq $b ] |
-ne |
Not equal to (numeric) | [ $a -ne $b ] |
-lt |
Less than (numeric) | [ $a -lt $b ] |
-le |
Less than or equal (numeric) | [ $a -le $b ] |
-gt |
Greater than (numeric) | [ $a -gt $b ] |
-ge |
Greater than or equal (numeric) | [ $a -ge $b ] |
= |
Equal to (string) | [ "$str1" = "$str2" ] |
!= |
Not equal to (string) | [ "$str1" != "$str2" ] |
-z |
String is empty | [ -z "$str" ] |
-n |
String is not empty | [ -n "$str" ] |
File Test Operators
| Operator | Description | Example |
|---|---|---|
-f |
File exists and is regular file | [ -f file.txt ] |
-d |
Directory exists | [ -d /path/dir ] |
-e |
File or directory exists | [ -e /path/item ] |
-r |
File is readable | [ -r file.txt ] |
-w |
File is writable | [ -w file.txt ] |
-x |
File is executable | [ -x script.sh ] |
-s |
File exists and is not empty | [ -s file.txt ] |
Examples
Basic if statement
Checks if the current user is root
if-else statement
Checks if a file exists with alternative action
if-elif-else statement
Multiple conditions with elif clauses
String comparison
Compares user input with a string
Numeric comparison
Compares numeric values
File existence check
Checks if file exists and performs actions
Directory check
Checks if directory exists before changing to it
Command success check
Tests command success using exit status
Multiple conditions with logical operators
Combines multiple conditions with AND operator
Empty string check
Checks if string is empty
Nested if statements
Nested conditions for complex logic
Using test command
Alternative syntax using test command
Advanced Usage
Pattern matching
Using [[ ]] for pattern matching (bash-specific)
Regular expressions
Using regular expressions with [[ ]] (bash-specific)
Common Use Cases
When to Use if Statements
- Input Validation - Check user input and command arguments
- File Operations - Verify file existence before processing
- Error Handling - Handle command failures gracefully
- Configuration - Adapt behavior based on system state
- Flow Control - Direct script execution based on conditions