Day 2: Understanding Conditionals in Shell Scripting (if, else, elif).

Day 2: Understanding Conditionals in Shell Scripting (if, else, elif).

Conditionals allow us to make decisions in your shell scripts. They let you run different blocks of code depending on whether a condition is true or false.

1. if Statement

#!/bin/bash
x=5
if [ $x -gt 3 ]; then
echo "x is greater than 3"
fi

[ $x -gt 3 ]: This is the condition.

2. else Statement
The else statement is used to specify what should happen if the if condition is false.

#!/bin/bash

x=2
if [ $x -gt 3 ]; then
echo "x is greater than 3"
else
echo "x is not greater than 3"
fi

3. elif Statement

elif (else if) is used to check multiple conditions. It runs if the first if condition is false but the elif condition is true.

#!/bin/bash
x=3
if [ $x -gt 3 ]; then
echo "x is greater than 3"
elif
[ $x -eq 3 ]; then echo "x is equal to 3"
else
echo "x is less than 3"
fi

4. Combining Multiple Conditions

You can combine conditions using && (AND) or || (OR).

AND (&&): All conditions must be true.

#!/bin/bash

#Initialize x with a value or get it from user input

x=1 # Example of initializing x with a default value

#Alternatively, you can prompt the user for input

#read -p "Enter the value of x: " x

#Ensure x is not empty and is a valid number

if [[ -n "$x" && "$x" =~ ^[0-9]+$ ]]; then
if [ "$x" -gt 2 ] && [ "$x" -lt 5 ]; then
echo "x is between 2 and 5"
else
echo "x is not between 2 and 5"
fi
else
echo "Error: x is not defined or is not a valid number"
fi

OR (||): At least one condition must be true.

#!/bin/bash

#Initialize x with a value or get it from user input

x=15 # Example of initializing x with a default value

#Alternatively, you can prompt the user for input

#read -p "Enter the value of x: " x

#Ensure x is not empty and is a valid number

if [[ -n "$x" && "$x" =~ ^[0-9]+$ ]]; then
if [ "$x" -lt 2 ] || [ "$x" -gt 10 ]; then
echo "x is either less than 2 or greater than 10"
else
echo "x is between 2 and 10"
fi
else
echo "Error: x is not defined or is not a valid number"
fi

  1. Conclusion

Today, we learned how to use if, else, and elif statements to make decisions in your scripts. we explored logical operators like AND (&&) and OR (||) and practiced handling different conditions. Input validation and quoting variables were emphasized to avoid errors.

If you have any questions or face issues, feel free to drop a comment below or mail me at !