Conditionals and Loops
Control flow structures let your scripts make decisions and repeat actions. They're the building blocks of useful automation.
If Statements
Basic syntax:
if [ condition ]; then
commands
fi
With else:
if [ condition ]; then
commands
else
other_commands
fi
With elif:
if [ condition1 ]; then
commands1
elif [ condition2 ]; then
commands2
else
default_commands
fi
Test Conditions
String Tests
| Test | Meaning |
|---|---|
[ -z "$STR" ] | String is empty |
[ -n "$STR" ] | String is not empty |
[ "$A" = "$B" ] | Strings are equal |
[ "$A" != "$B" ] | Strings are not equal |
Numeric Tests
| Test | Meaning |
|---|---|
[ $A -eq $B ] | Equal |
[ $A -ne $B ] | Not equal |
[ $A -lt $B ] | Less than |
[ $A -gt $B ] | Greater than |
[ $A -le $B ] | Less than or equal |
[ $A -ge $B ] | Greater than or equal |
File Tests
| Test | Meaning |
|---|---|
[ -e FILE ] | File exists |
[ -f FILE ] | Is a regular file |
[ -d FILE ] | Is a directory |
[ -r FILE ] | Is readable |
[ -w FILE ] | Is writable |
[ -x FILE ] | Is executable |
If Example
#!/bin/bash
FILE="/etc/hosts"
if [ -f "$FILE" ]; then
echo "File exists"
else
echo "File not found"
fi
Exercise: Check File Existence
Write a conditional to check if a file exists:
For Loops
Basic For Loop
for item in item1 item2 item3; do
echo "$item"
done
Loop Through Files
for file in *.txt; do
echo "Processing: $file"
done
C-style For Loop
for ((i=0; i<5; i++)); do
echo "Count: $i"
done
While Loops
COUNT=0
while [ $COUNT -lt 5 ]; do
echo "Count: $COUNT"
COUNT=$((COUNT + 1))
done
Reading File Line by Line
while read line; do
echo "$line"
done < file.txt
Until Loops
Runs until condition becomes true:
COUNT=0
until [ $COUNT -ge 5 ]; do
echo "Count: $COUNT"
COUNT=$((COUNT + 1))
done
Case Statements
Multiple choice selection:
case $1 in
start)
echo "Starting..."
;;
stop)
echo "Stopping..."
;;
*)
echo "Usage: $0 {start|stop}"
;;
esac
Loop Control
Break
Exit the loop:
for i in 1 2 3 4 5; do
if [ $i -eq 3 ]; then
break
fi
echo $i
done
# Outputs: 1 2
Continue
Skip to next iteration:
for i in 1 2 3 4 5; do
if [ $i -eq 3 ]; then
continue
fi
echo $i
done
# Outputs: 1 2 4 5
Combining Conditions
# AND
if [ condition1 ] && [ condition2 ]; then
echo "Both true"
fi
# OR
if [ condition1 ] || [ condition2 ]; then
echo "At least one true"
fi
# NOT
if [ ! condition ]; then
echo "Condition is false"
fi
[[ ]] vs [ ]
[[ ]] is more powerful (bash-specific):
# Pattern matching
if [[ $STRING == *"substring"* ]]; then
echo "Contains substring"
fi
# Regex
if [[ $STRING =~ ^[0-9]+$ ]]; then
echo "Is a number"
fi
Key Takeaways
- Use
if [ condition ]; then ... fifor conditionals - Test strings with
=, numbers with-eq,-lt, etc. - Test files with
-f,-d,-e - Use
forandwhilefor loops breakexits loops,continueskips iterationscasehandles multiple options elegantly

