This tutorial provides a comprehensive overview of IF-Else statements in BASH scripting. From the basics of condition testing to complex nested statements, we will explore a variety of applications using real-world examples.
Step 1: Introduction to IF-Else Statements
IF-Else statements are used in BASH for conditional execution of code. The structure is if [condition]; then commands; else commands; fi.
if [ "$a" -lt 20 ]; then
echo "a is less than 20"
else
echo "a is not less than 20"
fiPractice Exercise
Write a BASH script that prints 'Even' or 'Odd' for a given number.
Show Solution
if [ $(($number%2)) -eq 0 ]; then
echo "Even"
else
echo "Odd"
fiStep 2: Understanding the Condition Bracket
The condition in an IF-Else statement is enclosed in square brackets. The left bracket [ is actually a command that returns a status. A space must be included after [ and before ].
if [ "$a" -lt 20 ]; then
# commands
fiPractice Exercise
Fix the following incorrect BASH IF-Else statement: if [$a -lt 20]; then echo "Correct"; fi
Show Solution
if [ $a -lt 20 ]; then
echo "Correct"
fiStep 3: Elif Statements
Elif (else if) is used for multiple conditions. It allows for more complex conditional branches.
if [ "$a" -lt 20 ]; then
# commands
elif [ "$a" -eq 20 ]; then
# commands
else
# commands
fiPractice Exercise
Write a BASH script that categorizes a person's age as 'Child', 'Teen', 'Adult', or 'Senior'.
Show Solution
if [ $age -lt 13 ]; then
echo "Child"
elif [ $age -lt 20 ]; then
echo "Teen"
elif [ $age -lt 65 ]; then
echo "Adult"
else
echo "Senior"
fiStep 4: Nested IF-Else Statements
Nested IF-Else statements involve placing an IF-Else statement within another. This allows for even more complex decision-making.
if [ "$a" -lt 20 ]; then
if [ "$a" -gt 10 ]; then
# commands
fi
fiPractice Exercise
Create a BASH script that checks if a number is within the range 10-20, inclusive. Print a specific message for each condition.
Show Solution
if [ $number -le 20 ]; then
if [ $number -ge 10 ]; then
echo "Number is within range."
else
echo "Number is less than range."
fi
else
echo "Number is greater than range."
fiStep 5: Combining Conditions
Conditions can be combined using AND (-a or &&) and OR (-o or ||) operators.
if [ "$a" -gt 10 -a "$a" -lt 20 ]; then
# commands
fiPractice Exercise
Write a BASH script that checks if a number is between 10-20 or 30-40.
Show Solution
if [ $number -ge 10 -a $number -le 20 ] || [ $number -ge 30 -a $number -le 40 ]; then
echo "Number is within range."
else
echo "Number is out of range."
fiSign in to take Cornell notes on this lesson — they save automatically and stay with your account.