In this comprehensive tutorial, we will delve into the Bash if elif else statement, a crucial control structure in shell scripting. Bash, an acronym for Bourne-Again SHell, is a Unix shell and command-line interpreter that has become the default shell for many Linux distributions and macOS. Mastering the if elif else statement will greatly enhance your ability to write efficient and flexible shell scripts.
1. Understanding Bash if elif else Statement
The if elif else statement is a control structure that allows you to execute a block of code based on whether a given condition is true or false. It provides a way to make decisions within your shell script and perform different actions based on the outcome of these decisions. The if statement checks a condition, while the elif (short for “else if”) and else clauses provide alternative code blocks to execute when the initial condition is false.
2. Basic Syntax of Bash if elif else Statement
The general syntax for the if elif else statement in Bash is as follows:
if [CONDITION]; then
# Code block to execute if CONDITION is true
elif [ANOTHER_CONDITION]; then
# Code block to execute if ANOTHER_CONDITION is true
else
# Code block to execute if all previous conditions are false
fi
3. Bash if Statement
3.1 Simple if Statement
The simplest form of the if statement checks a single condition and executes a block of code only when the condition is true.
Example:
#!/bin/bash
number=10
if [ $number -eq 10 ]; then
echo "The number is equal to 10."
fi
This script checks if a given number is equal to 10 and prints a message if the condition is true.
3.2 if-else Statement
The if-else statement checks a condition and executes one block of code when the condition is true and another block when the condition is false.
Example:
#!/bin/bash
number=5
if [ $number -gt 10 ]; then
echo "The number is greater than 10."
else
echo "The number is not greater than 10."
fi
This script checks if a given number is greater than 10, prints a message if the condition is true, and prints an alternative message if the condition is false.
4. Bash elif Statement
The elif clause provides a way to test multiple conditions sequentially. When using elif, the first condition that evaluates to true will execute its associated code block, and the rest will be skipped.
Example:
#!/bin/bash
number=15
if [ $number -lt 10 ]; then
echo "The number is less than 10."
elif [ $number -eq 10 ]; then
echo "The number is equal to 10."
else
echo "The number is greater than 10."
fi
This script checks if a given number is less than, equal to, or greater than 10, and prints an appropriate message based on the evaluation.
5. Combining Conditions with AND and OR Operators
You can use the logical AND (-a
or &&
) and logical OR (-o
or ||
) operators to combine conditions in your if statements.
Example:
#!/bin/bash
number=25
if [ $number -gt 10 ] && [ $number -lt 20 ]; then
echo "The number is between 10 and 20."
else
echo "The number is not between 10 and 20."
fi
This script checks if a given number is between 10 and 20 using the AND operator, and prints a message based on the evaluation.
6. Testing Multiple Conditions with elif
You can use multiple elif clauses to test a series of conditions in sequence. If any condition evaluates to true, its associated code block will execute, and the rest of the conditions will be skipped.
Example:
#!/bin/bash
number=45
if [ $number -lt 20 ]; then
echo "The number is less than 20."
elif [ $number -ge 20 ] && [ $number -lt 40 ]; then
echo "The number is between 20 and 40."
elif [ $number -ge 40 ] && [ $number -lt 60 ]; then
echo "The number is between 40 and 60."
else
echo "The number is greater than or equal to 60."
fi
This script checks if a given number falls within different specified ranges, and prints a message based on the evaluation.
7. Nested if Statements
You can use nested if statements to create more complex decision-making structures in your shell scripts. This involves placing an if statement within another if statement.
Example:
#!/bin/bash
number=15
if [ $(($number % 2)) -eq 0 ]; then
echo "The number is even."
if [ $(($number % 4)) -eq 0 ]; then
echo "The number is also divisible by 4."
else
echo "The number is not divisible by 4."
fi
else
echo "The number is odd."
if [ $(($number % 3)) -eq 0 ]; then
echo "The number is also divisible by 3."
else
echo "The number is not divisible by 3."
fi
fi
This script checks if a given number is even or odd using an if-else statement. Inside each branch, a nested if-else statement checks if the number is divisible by 4 (if even) or divisible by 3 (if odd), and prints appropriate messages based on the evaluations.
8. Practical Examples
Let’s look at a few practical examples of using if elif else statements in Bash shell scripts.
Example 1: User input validation
#!/bin/bash
read -p "Enter a number between 1 and 10: " number
if [ $number -ge 1 ] && [ $number -le 10 ]; then
echo "Valid input."
else
echo "Invalid input. Please enter a number between 1 and 10."
fi
This script prompts the user to enter a number between 1 and 10, validates the input, and prints a message based on the validation result.
Example 2: File existence check
#!/bin/bash
file_path="example.txt"
if [ -f "$file_path" ]; then
echo "The file exists."
else
echo "The file does not exist."
fi
This script checks if a specified file exists and prints a message based on the file’s existence.
Conclusion
The Bash if elif else statement is a powerful control structure that allows you to create complex decision-making processes in your shell scripts. Understanding and using this statement effectively will greatly enhance your ability to write efficient and flexible scripts. Practice using different conditions, operators, and nesting techniques to become proficient in using the Bash if elif else statement.
3 Comments
How would I combine commands in a code block? Is it done using indentation like in Python?
Thank you for the examples.
I’m trying to build a backup bash script that also save progress to a log file and later send an email to confirm success or failure.
All the backup parts work, but my IF fails. If first looked at using $? to check for success, but sqldump creates a file even if the DB is not accessible. Now I’m trying to check of file size using $du -k file_name | cut -f 1 and this works giving the file size. The issue is the if do not seem to work.
if ($actualsize -gt $minsize) then
echo “bla bla bla” >> /var/log/backup.log
else
echo “bla bla” >> /var/log/backup.log
fi
I would also like to have an error counter as I’m backup multiple DB’s and folders.
Any advice?
Hi Deon, You are using wrong braces in if condition. Also use ; when using then in same line. Hope this helps you.
if [ $actualsize -gt $minsize ]; then
echo “bla bla bla” >> /var/log/backup.log
else
echo “bla bla” >> /var/log/backup.log
fi