Shell Scripting - Part 3
In shell scripting, conditional statements are used to perform different actions based on certain conditions. The most commonly used conditional statements in shell scripting are the if statement and the case statement. Here's how you can use them:
- if statement: The
ifstatement allows you to execute a block of code based on the result of a condition. It has the following syntax:
if [ condition ]; then
# code to be executed if the condition is true
else
# code to be executed if the condition is false
fi
The [ condition ] part can contain various comparison operators such as -eq (equal), -ne (not equal), -gt (greater than), -lt (less than), etc. Additionally, you can use logical operators like -a (and), -o (or), ! (not) to combine conditions.
Here's an example:
#!/bin/bash
age=18
if [ $age -ge 18 ]; then
echo "You are eligible to vote."
else
echo "You are not eligible to vote."
fi
Real World Scenario: You're working as an AWS administrator and you need to pull a weekly report to check all the EC2 instances in all regions. Your manager asked you to create a shell script.



- case statement: The
casestatement is used when you have multiple conditions to check against a variable or an expression. It has the following syntax:
Here's an example:
#!/bin/bash
fruit="apple"
case $fruit in
"apple")
echo "It's an apple."
;;
"banana")
echo "It's a banana."
;;
"orange")
echo "It's an orange."
;;
*)
echo "It's an unknown fruit."
;;
esac
For example, you want to create a customer script which pulls the instance status just by running script and a command fetch using case statement. Below is the script.


These are the basic conditional statements in shell scripting. They allow you to control the flow of your script based on specific conditions.