In shell scripting, control structures enable you to make decisions, repeat tasks, and handle different scenarios. This guide covers the following control structures:
Conditional statements allow you to execute different sets of commands based on certain conditions. The basic syntax for an if-else statement is as follows:
if [ condition ]; then
# commands to execute if the condition is true
else
# commands to execute if the condition is false
fi#!/bin/bash
age=20
if [ $age -ge 18 ]; then
echo "You are eligible to vote."
else
echo "You are not eligible to vote yet."
fiIn this example, the script checks if the variable age is greater than or equal to 18 and prints a message accordingly.
Loops allow you to repeat a set of commands multiple times. There are different types of loops, such as for and while loops.
The for loop iterates over a sequence of values. The basic syntax is as follows:
for variable in value1 value2 ... valuen; do
# commands to execute for each value
done#!/bin/bash
for i in {1..5}; do
echo "Number: $i"
doneThis script uses a for loop to print numbers from 1 to 5.
The while loop continues executing commands as long as a specified condition is true. The basic syntax is as follows:
while [ condition ]; do
# commands to execute as long as the condition is true
done#!/bin/bash
count=5
while [ $count -gt 0 ]; do
echo "Countdown: $count"
((count--))
doneThis script uses a while loop to count down from 5 to 1.
Case statements provide a way to perform different actions based on the value of a variable. The basic syntax is as follows:
case variable in
pattern1)
# commands for pattern1
;;
pattern2)
# commands for pattern2
;;
*)
# commands for any other pattern
;;
esac#!/bin/bash
day="Monday"
case $day in
"Monday"|"Tuesday"|"Wednesday"|"Thursday"|"Friday")
echo "It's a weekday."
;;
"Saturday"|"Sunday")
echo "It's a weekend."
;;
*)
echo "Invalid day."
;;
esacThis script uses a case statement to determine whether a given day is a weekday or weekend.
These examples illustrate the usage of control structures in shell scripting. Feel free to modify and experiment with the provided code.
- Conditional Statements: Use if, elif, and else for decision-making based on conditions.
- Loops: Use for and while loops for repetitive tasks.
- Case Statements: Use case for multiple condition matching.