Linux / Bash
Beginner
1 min read
Bash Control Flow: if, for, and while
Example
#!/bin/bash
# ---- if / elif / else ----
FILE="/etc/hosts"
if [[ -f "$FILE" ]]; then
echo "$FILE exists and is a regular file"
elif [[ -d "$FILE" ]]; then
echo "$FILE is a directory"
else
echo "$FILE does not exist"
fi
# String comparison
USER_INPUT="yes"
if [[ "$USER_INPUT" == "yes" ]]; then
echo "User agreed"
fi
# Numeric comparison (-eq -ne -lt -le -gt -ge)
COUNT=5
if (( COUNT > 3 )); then
echo "Count is greater than 3"
fi
# ---- for loop ----
# Over a list
for fruit in apple banana cherry; do
echo "Fruit: $fruit"
done
# Over a range
for i in {1..5}; do
echo "Iteration $i"
done
# Over files
for f in /etc/*.conf; do
echo "Config file: $f"
done
# C-style
for (( i=0; i<3; i++ )); do
echo "Index $i"
done
# ---- while loop ----
counter=1
while (( counter <= 3 )); do
echo "Counter: $counter"
(( counter++ ))
done
# Read file line by line
while IFS= read -r line; do
echo "Line: $line"
done < /etc/hosts
# ---- case statement ----
DAY=$(date +%A)
case "$DAY" in
Monday|Tuesday|Wednesday|Thursday|Friday)
echo "Weekday" ;;
Saturday|Sunday)
echo "Weekend" ;;
*)
echo "Unknown" ;;
esac
Related Resources
Linux / Bash Reference
Complete tag & property list
Linux / Bash How-To Guides
Step-by-step practical guides
Linux / Bash Exercises
Practice what you've learned
More in Linux / Bash