Discuss the control structures available in shell scripting and provide examples of their usage.
Control structures in shell scripting allow you to control the flow of execution based on conditions, perform repetitive tasks, and make decisions. The common control structures in shell scripting are:
1. if-else Statement:
* The if-else statement allows you to execute different code blocks based on a condition.
* Syntax:
```
bash`if condition
then
# Code block executed if the condition is true
else
# Code block executed if the condition is false
fi`
```
* Example:
```
bash`# Check if a file exists and display a message accordingly
if [ -f "myfile.txt" ]
then
echo "File exists"
else
echo "File does not exist"
fi`
```
2. for Loop:
* The for loop is used to iterate over a sequence of values or a list of items.
* Syntax:
```
bash`for variable in sequence
do
# Code block executed for each value in the sequence
done`
```
* Example:
```
bash`# Iterate over a list of filenames and display each one
for file in file1.txt file2.txt file3.txt
do
echo "File: $file"
done`
```
3. while Loop:
* The while loop allows you to repeatedly execute a code block as long as a condition is true.
* Syntax:
```
bash`while condition
do
# Code block executed while the condition is true
done`
```
* Example:
```
bash`# Count down from 5 to 1
count=5
while [ $count -gt 0 ]
do
echo $count
count=$((count - 1))
done`
```
4. until Loop:
* The until loop is similar to the while loop but continues executing a code block until a condition becomes true.
* Syntax:
```
bash`until condition
do
# Code block executed until the condition is true
done`
```
* Example:
```
bash`# Generate random numbers until a number less than 5 is generated
number=0
until [ $number -lt 5 ]
do
number=$((RANDOM % 10))
echo $number
done`
```
5. case Statement:
* The case statement allows you to perform different actions based on the value of a variable.
* Syntax:
```
bash`case variable in
pattern1)
# Code block executed for pattern1
;;
pattern2)
# Code block executed for pattern2
;;
*)
# Code block executed for all other patterns
;;
esac`
```
* Example:
```
bash`# Check the day of the week and perform different actions
day=$(date +%u)
case $day in
1)
echo "Today is Monday"
;;
2)
echo "Today is Tuesday"
;;
*)
echo "Today is neither Monday nor Tuesday"
;;
esac`
```
These control structures allow you to create conditional statements, perform iterations, and make decisions based on specific conditions. By utilizing these structures, you can create powerful and flexible shell scripts that automate tasks, handle various scenarios, and respond dynamically to different conditions and inputs.