USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Control Structures and Functions

Lesson 14/32 | Study Time: 20 Min

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.

bash
if [ condition ]; then
commands
fi


2. If-Else Statement:

Executes commands in the ‘then’ block if true; otherwise, executes the ‘else’ block.

bash
if [ condition ]; then
commands
else
commands
fi


3. If-Elif-Else Ladder:

Allows testing multiple conditions sequentially.

bash
if [ condition1 ]; then
commands
elif [ condition2 ]; then
commands
else
commands
fi


Example:

bash
if [ "$age" -ge 18 ]; then
echo "Adult"
elif [ "$age" -ge 13 ]; then
echo "Teenager"
else
echo "Child"
fi


4. Case Statement:

Multi-way branch, similar to switch in other languages.

bash
case "$variable" in
pattern1)
commands;;
pattern2)
commands;;
*)
commands;;
esac

Control Structures: Looping

Loops repeat commands until a condition is met or a sequence ends.


1. For Loop:

Iterates over a list of values.

Syntax:

bash
for var in list; do
commands
done


Example:

bash
for file in *.txt; do
echo "Processing $file"
done


2. While Loop:

Repeats while a condition is true.

bash
while [ condition ]; do
commands
done


Example:

bash
count=1
while [ $count -le 5 ]; do
echo "Count $count"
((count++))
done


3. Until Loop:

Repeats until a condition becomes true.

bash
until [ condition ]; do
commands
done


4. Break and Continue:


break: exits the loop early.

continue: skips to next iteration.


Example:

bash
for i in {1..10}; do
if [ $i -eq 5 ]; then
break
fi
echo $i
done

Functions in Shell Scripts

Functions encapsulate commands for reuse and better organization.


1. Define functions with:

bash
function name() {
commands
}


or

bash
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:

bash
greet() {
echo "Hello, $1!"
}
greet "Alice"


Functions allow modular scripts, easier maintenance, and repeating logic without duplication.