Conditionals and Loops
if/elif/else, for, while, test expressions, and [[ ... ]] conditions
Skills taught: linux.if-else, linux.for-loop, linux.while-loop, linux.test-expressions
if / elif / else
#!/usr/bin/env bash
# [[ ]] is the modern bash conditional (prefer over [ ])
FILE="config.txt"
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
# Common file tests:
# -f file exists and is a regular file
# -d directory exists
# -e file/directory exists
# -r readable, -w writable, -x executable
# -s file exists and is not empty
# String comparisons:
if [[ "$NAME" == "Alice" ]]; then echo "Hi Alice"; fi
if [[ "$NAME" != "" ]]; then echo "Name is set"; fi
if [[ -z "$NAME" ]]; then echo "Name is empty"; fi # -z = zero length
if [[ -n "$NAME" ]]; then echo "Name is set"; fi # -n = non-empty
# Number comparisons:
if [[ $AGE -gt 18 ]]; then echo "Adult"; fi
# -gt greater than, -lt less than, -ge >=, -le <=, -eq ==, -ne !=
for loops
#!/usr/bin/env bash
# Loop over a list
for NAME in Alice Bob Carol; do
echo "Hello, $NAME!"
done
# Loop over files
for FILE in *.log; do
echo "Processing: $FILE"
gzip "$FILE" # compress each log file
done
# Loop over a range of numbers
for i in {1..5}; do
echo "Iteration $i"
done
# C-style for loop
for (( i=0; i<5; i++ )); do
echo "$i"
done
# Loop over command output
for FILE in $(find . -name '*.json'); do
echo "Found: $FILE"
done
# Loop over script arguments
for ARG in "$@"; do
echo "Arg: $ARG"
done
while loops
#!/usr/bin/env bash
# while: loop while condition is true
COUNT=0
while [[ $COUNT -lt 5 ]]; do
echo "Count: $COUNT"
(( COUNT++ )) # increment
done
# Read file line by line
while IFS= read -r LINE; do
echo "Line: $LINE"
done < input.txt
# Wait for a service to be ready
until curl -s http://localhost:3000/health; do
echo "Waiting for server..."
sleep 2
done
echo "Server is ready!"
# Infinite loop with break
while true; do
if [[ -f /tmp/stop ]]; then
break
fi
echo "Running..."
sleep 10
done
Frequently Asked Questions
What is the difference between [ ] and [[ ]]?
[ ] is the POSIX test command — works in all shells but has edge cases with spaces in variable names (use quotes: [ "$VAR" ]). [[ ]] is a bash/zsh keyword — safer (no word splitting), supports &&/||/=~, and doesn't require quoting variables for most comparisons. Always use [[ ]] in bash scripts.