Skip to main content

Chapter 6.3 - Control Structures

Learning Objectives​

By the end of this chapter, you will be able to:

  • Use if/else conditions
  • Implement for and while loops
  • Use case for multiple selection
  • Understand test operators
  • Handle errors

if/else Conditions​

Basic Syntax​

#!/bin/bash
# simple if
if [ condition ]; then
commands
fi

# if/else
if [ condition ]; then
commands_if_true
else
commands_if_false
fi

# if/elif/else
if [ condition1 ]; then
commands1
elif [ condition2 ]; then
commands2
else
commands3
fi

Test Operators​

Files:

[ -f file ]      # File exists and is regular
[ -d directory ] # Directory exists
[ -e path ] # Path exists
[ -r file ] # Readable
[ -w file ] # Writable
[ -x file ] # Executable
[ -s file ] # Not empty

Strings:

[ -z "$VAR" ]       # Empty
[ -n "$VAR" ] # Not empty
[ "$VAR1" = "$VAR2" ] # Equal
[ "$VAR1" != "$VAR2" ] # Not equal

Numbers:

[ $A -eq $B ]       # Equal
[ $A -ne $B ] # Not equal
[ $A -lt $B ] # Less than
[ $A -le $B ] # Less than or equal
[ $A -gt $B ] # Greater than
[ $A -ge $B ] # Greater than or equal

Logic:

[ condition1 ] && [ condition2 ]  # AND
[ condition1 ] || [ condition2 ] # OR
[ ! condition ] # NOT

Examples​

#!/bin/bash
# Check file
if [ -f "/etc/passwd" ]; then
echo "File exists"
else
echo "File does not exist"
fi

# Check user
if [ "$USER" = "root" ]; then
echo "You are root"
elif [ "$UID" -eq 0 ]; then
echo "You are root (by UID)"
else
echo "You are $USER"
fi

# Multiple conditions
if [ -f "$1" ] && [ -r "$1" ]; then
echo "File exists and is readable"
fi

for Loop​

Syntax​

#!/bin/bash
# List of values
for item in value1 value2 value3; do
echo "Item: $item"
done

# Iterate over arguments
for arg in "$@"; do
echo "Argument: $arg"
done

# Numeric sequence
for i in {1..10}; do
echo "Number: $i"
done

# With increment
for i in {1..10..2}; do
echo "Number: $i"
done

# C-style
for ((i=1; i<=10; i++)); do
echo "Number: $i"
done

Examples​

#!/bin/bash
# Iterate over files
for file in *.txt; do
echo "Processing: $file"
# Processing...
done

# Iterate over directories
for dir in /home/*; do
if [ -d "$dir" ]; then
echo "Directory: $dir"
fi
done

# Iterate over array
FRUITS=("apple" "banana" "orange")
for fruit in "${FRUITS[@]}"; do
echo "Fruit: $fruit"
done

while Loop​

Syntax​

#!/bin/bash
# simple while
while [ condition ]; do
commands
done

# while with reading
while read line; do
echo "Line: $line"
done < file.txt

# infinite while
while true; do
commands
sleep 1
done

Examples​

#!/bin/bash
# Counter
i=1
while [ $i -le 10 ]; do
echo "Number: $i"
i=$((i + 1))
done

# Read file line by line
while IFS= read -r line; do
echo "Line: $line"
done < /etc/passwd

# Interactive menu
while true; do
echo "1. Option 1"
echo "2. Option 2"
echo "3. Quit"
read -p "Choice: " choice

case $choice in
1) echo "Option 1" ;;
2) echo "Option 2" ;;
3) break ;;
*) echo "Invalid choice" ;;
esac
done

until Loop​

#!/bin/bash
# until (until condition is true)
i=1
until [ $i -gt 10 ]; do
echo "Number: $i"
i=$((i + 1))
done

case - Multiple Selection​

Syntax​

#!/bin/bash
case $variable in
pattern1)
commands1
;;
pattern2)
commands2
;;
pattern3|pattern4)
commands3
;;
*)
default_commands
;;
esac

Examples​

#!/bin/bash
# Simple menu
read -p "Choice (1-3): " choice

case $choice in
1)
echo "Option 1 selected"
;;
2)
echo "Option 2 selected"
;;
3)
echo "Option 3 selected"
;;
*)
echo "Invalid choice"
exit 1
;;
esac

# Patterns with wildcards
case "$1" in
start)
echo "Starting"
;;
stop)
echo "Stopping"
;;
restart|reload)
echo "Restarting"
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
;;
esac

Flow Control​

break and continue​

#!/bin/bash
# break: Exit the loop
for i in {1..10}; do
if [ $i -eq 5 ]; then
break
fi
echo $i
done

# continue: Skip to the next iteration
for i in {1..10}; do
if [ $i -eq 5 ]; then
continue
fi
echo $i
done

exit​

#!/bin/bash
# exit: Exit the script
if [ ! -f "$1" ]; then
echo "Error: File not found"
exit 1
fi

# Return code
exit 0 # Success
exit 1 # General error
exit 2 # Specific error

Complete Example​

#!/bin/bash
# File processing script

# Check arguments
if [ $# -eq 0 ]; then
echo "Usage: $0 FILE..."
exit 1
fi

# Process each file
for file in "$@"; do
# Check existence
if [ ! -f "$file" ]; then
echo "Warning: $file does not exist, ignored"
continue
fi

# Check permissions
if [ ! -r "$file" ]; then
echo "Error: $file is not readable"
continue
fi

# Process according to extension
case "$file" in
*.txt)
echo "Text processing: $file"
# Processing...
;;
*.log)
echo "Log processing: $file"
# Processing...
;;
*)
echo "Unsupported type: $file"
;;
esac
done

echo "Processing completed"

Summary​

In this chapter, you learned:

if/else: Conditions with test operators
for: Loops with lists, sequences, arrays
while: Conditional loops, file reading
case: Multiple selection with patterns
Control: break, continue, exit
Operators: Files, strings, numbers, logic


Next Steps​

Chapter 6.4: Functions and Cron
Module 7: Networking and Configuration


Chapter created on: December 2024