Control structures are essential components of shell scripting that allow you to control the flow of your script's execution. They enable you to make decisions, repeat actions, and create more complex and powerful scripts. In this article, we'll explore the primary control structures in Bash scripting.
If-else statements allow your script to make decisions based on conditions. Here's the basic syntax:
if [ condition ]; then
# Commands to execute if condition is true
elif [ another_condition ]; then
# Commands to execute if another_condition is true
else
# Commands to execute if all conditions are false
fi
Example:
#!/bin/bash
age=25
if [ $age -lt 18 ]; then
echo "You are a minor."
elif [ $age -ge 18 ] && [ $age -lt 65 ]; then
echo "You are an adult."
else
echo "You are a senior citizen."
fi
Case statements are useful when you need to match a variable against several values. They're often cleaner than multiple if-elif statements.
case $variable in
pattern1)
# Commands for pattern1
;;
pattern2)
# Commands for pattern2
;;
*)
# Default case
;;
esac
Example:
#!/bin/bash
fruit="apple"
case $fruit in
"apple")
echo "It's an apple."
;;
"banana"|"plantain")
echo "It's a banana or plantain."
;;
*)
echo "Unknown fruit."
;;
esac
For loops are used to iterate over a list of items or a range of numbers.
for item in list
do
# Commands to execute for each item
done
Example:
#!/bin/bash
for color in red green blue
do
echo "Color: $color"
done
While loops execute a set of commands as long as a condition is true.
while [ condition ]
do
# Commands to execute
done
Example:
#!/bin/bash
count=1
while [ $count -le 5 ]
do
echo "Count: $count"
((count++))
done
Until loops are similar to while loops, but they execute until a condition becomes true.
until [ condition ]
do
# Commands to execute
done
Example:
#!/bin/bash
count=1
until [ $count -gt 5 ]
do
echo "Count: $count"
((count++))
done
'break' is used to exit a loop prematurely, while 'continue' skips the rest of the current iteration and moves to the next one.
#!/bin/bash
for num in 1 2 3 4 5
do
if [ $num -eq 3 ]; then
continue
fi
if [ $num -eq 5 ]; then
break
fi
echo "Number: $num"
done
Let's combine these concepts into a practical script:
#!/bin/bash
echo "Enter a filename:"
read filename
if [ -f "$filename" ]; then
echo "$filename is a regular file."
case $(file -b "$filename") in
*text*)
echo "It's a text file."
;;
*image*)
echo "It's an image file."
;;
*)
echo "It's another type of file."
;;
esac
elif [ -d "$filename" ]; then
echo "$filename is a directory."
else
echo "$filename does not exist."
fi
Control structures are powerful tools in shell scripting that allow you to create dynamic and responsive scripts. Practice using these structures to enhance your scripting skills and create more sophisticated Bash programs.
In our next article, we'll explore shell script functions and how they can help you organize and reuse your code. Stay tuned!