Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Bash if elif else Statement A Comprehensive Tutorial
The Bash if-elif-else statement is a fundamental control structure that allows you to execute different blocks of code based on conditions. This conditional construct enables you to create decision-making logic in your Bash scripts, making them more dynamic and responsive to different scenarios.
What is Bash if-elif-else Statement?
The Bash if-elif-else statement evaluates conditions sequentially and executes the code block associated with the first true condition. If a condition is true, the corresponding code block runs and the remaining conditions are skipped. If none of the conditions are true, the else block executes (if present).
Syntax of Bash if-elif-else Statement
The basic syntax structure is straightforward and follows this pattern:
if [ condition1 ]; then # Code to be executed if condition1 is true elif [ condition2 ]; then # Code to be executed if condition2 is true else # Code to be executed if all conditions are false fi
Key Components:
if [ condition1 ]Tests the first condition using square bracketsthenIndicates the start of the code block to executeelif [ condition2 ]Optional; tests additional conditionselseOptional; executes when all conditions are falsefiMarks the end of the if statement
Examples of Bash if-elif-else Statement
Example 1: File Existence Check
if [ -e file.txt ]; then echo "The file exists" else echo "The file does not exist" fi
This example uses the -e test operator to check if file.txt exists in the current directory.
Example 2: Number Classification
read -p "Enter a number: " num if [ $num -gt 0 ]; then echo "The number is positive" elif [ $num -lt 0 ]; then echo "The number is negative" else echo "The number is zero" fi
This script uses comparison operators (-gt for greater than, -lt for less than) to classify a number as positive, negative, or zero.
Example 3: String Empty Check
read -p "Enter a string: " str if [ -z "$str" ]; then echo "The string is empty" else echo "The string is not empty" fi
The -z operator tests whether a string is empty (zero length).
Example 4: User Existence Verification
read -p "Enter username: " username if id "$username" >/dev/null 2>&1; then echo "The user exists" else echo "The user does not exist" fi
This example uses the id command to check if a user exists, redirecting output to /dev/null to suppress messages.
Advanced Usage Examples
File Permission Check
if [ -x file.sh ]; then ./file.sh else echo "The file does not have execute permission" fi
Pattern Matching with Regular Expressions
read -p "Enter a string: " str if [[ "$str" =~ ^[A-Za-z]+$ ]]; then echo "The string contains only letters" else echo "The string does not contain only letters" fi
File Comparison
if [ file1 -nt file2 ]; then echo "file1 is newer than file2" else echo "file2 is newer than or equal to file1" fi
Common Test Operators
| Operator | Description | Example |
|---|---|---|
| -e | File exists | [ -e file.txt ] |
| -f | Regular file exists | [ -f script.sh ] |
| -d | Directory exists | [ -d /home/user ] |
| -r | File is readable | [ -r config.txt ] |
| -w | File is writable | [ -w data.log ] |
| -x | File is executable | [ -x program ] |
| -z | String is empty | [ -z "$var" ] |
| -n | String is not empty | [ -n "$var" ] |
Best Practices
Quote variables Always enclose variables in double quotes to prevent issues with spaces and special characters
Use descriptive conditions Write clear, self-documenting conditional expressions
Proper indentation Maintain consistent indentation for better readability
Test thoroughly Validate your scripts with various input scenarios before deployment
Conclusion
The Bash if-elif-else statement is essential for creating intelligent scripts that respond to different conditions. By mastering this control structure and its various test operators, you can build robust automation scripts that handle multiple scenarios effectively.
