Control structures and functions form the backbone of shell scripting, enabling scripts to make decisions, repeat tasks, and organize code for reuse and clarity.
Control structures like conditionals and loops guide the flow of script execution based on logical tests, while functions allow grouping commands into reusable blocks.
Knowing of these constructs enables the creation of dynamic, flexible, and maintainable scripts that can handle complex automation and system administration tasks efficiently.
Control Structures: Conditional Statements
Conditional statements allow scripts to execute different commands based on whether a condition is true or false.
1. If Statement:
Executes commands only if a condition is true.
if [ condition ]; then
commands
fi2. If-Else Statement:
Executes commands in the ‘then’ block if true; otherwise, executes the ‘else’ block.
if [ condition ]; then
commands
else
commands
fi3. If-Elif-Else Ladder:
Allows testing multiple conditions sequentially.
if [ condition1 ]; then
commands
elif [ condition2 ]; then
commands
else
commands
fiExample:
if [ "$age" -ge 18 ]; then
echo "Adult"
elif [ "$age" -ge 13 ]; then
echo "Teenager"
else
echo "Child"
fi4. Case Statement:
Multi-way branch, similar to switch in other languages.
case "$variable" in
pattern1)
commands;;
pattern2)
commands;;
*)
commands;;
esacControl Structures: Looping
Loops repeat commands until a condition is met or a sequence ends.
1. For Loop:
Iterates over a list of values.
Syntax:
for var in list; do
commands
doneExample:
for file in *.txt; do
echo "Processing $file"
done2. While Loop:
Repeats while a condition is true.
while [ condition ]; do
commands
doneExample:
count=1
while [ $count -le 5 ]; do
echo "Count $count"
((count++))
done3. Until Loop:
Repeats until a condition becomes true.
until [ condition ]; do
commands
done4. Break and Continue:
break: exits the loop early.
continue: skips to next iteration.
Example:
for i in {1..10}; do
if [ $i -eq 5 ]; then
break
fi
echo $i
doneFunctions in Shell Scripts
Functions encapsulate commands for reuse and better organization.
1. Define functions with:
function name() {
commands
}or
name() {
commands
}2. Call functions by their name.
3. Functions can accept parameters via $1, $2, etc.
4. Return values using return or printing output.
Example:
greet() {
echo "Hello, $1!"
}
greet "Alice"Functions allow modular scripts, easier maintenance, and repeating logic without duplication.