Control Structures in Shell Scripting
This tutorial provides a comprehensive guide to using control structures in shell scripts, including conditional statements, loops, and case statements.
1. Introduction to Control Structures
Control structures are essential for directing the flow of a shell script. They allow you to make decisions, repeat tasks, and execute different parts of the script based on conditions.
2. Conditional Statements
Conditional statements execute code blocks based on specified conditions.
2.1. if Statement
The if
statement executes a block of code if a specified condition is true:
#!/bin/bash
num=5
if [ $num -gt 0 ]; then
echo "The number is positive"
fi
2.2. if-else Statement
The if-else
statement executes one block of code if a condition is true and another block if it is false:
#!/bin/bash
num=-5
if [ $num -gt 0 ]; then
echo "The number is positive"
else
echo "The number is not positive"
fi
2.3. if-elif-else Statement
The if-elif-else
statement allows for multiple conditions to be checked in sequence:
#!/bin/bash
num=0
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
3. Loops
Loops allow you to repeat a block of code multiple times.
3.1. for Loop
The for
loop iterates over a list of items and executes a block of code for each item:
#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number: $i"
done
3.2. while Loop
The while
loop executes a block of code as long as a specified condition is true:
#!/bin/bash
counter=1
while [ $counter -le 5 ]; do
echo "Counter: $counter"
((counter++))
done
3.3. until Loop
The until
loop executes a block of code as long as a specified condition is false:
#!/bin/bash
counter=1
until [ $counter -gt 5 ]; do
echo "Counter: $counter"
((counter++))
done
4. Case Statements
The case
statement allows you to execute different blocks of code based on the value of a variable:
#!/bin/bash
echo "Enter a number between 1 and 3:"
read num
case $num in
1)
echo "You entered one";;
2)
echo "You entered two";;
3)
echo "You entered three";;
*)
echo "Invalid input";;
esac
5. Conclusion
In this tutorial, you learned about various control structures in shell scripting, including conditional statements, loops, and case statements. These control structures are fundamental for writing complex and functional shell scripts, allowing you to control the flow of your script based on different conditions and iterate over data.