Bash Scripting Basics
Conditionals and Loops
Decision-making and repetition turn scripts into real programs.
The if statement
#!/bin/bash
file="notes.txt"
if [ -f "$file" ]; then
echo "$file exists"
else
echo "$file does not exist"
fi
The [ ... ] is the test command. Common tests:
| Test | True when |
|---|---|
-f file |
file exists and is a regular file |
-d dir |
dir exists and is a directory |
-e path |
the path exists (any type) |
$a -eq $b |
numbers are equal (-ne, -gt, -lt also exist) |
"$a" = "$b" |
strings are equal (!= for not equal) |
Quote your variables
Always wrap variables in quotes inside tests: [ "$name" = "Ada" ]. Unquoted empty variables can make the test fail or misbehave.
The for loop
#!/bin/bash
for name in Ada Grace Alan; do
echo "Hello, $name"
done
A very common pattern — act on every .txt file:
for file in *.txt; do
echo "Processing $file"
wc -l "$file"
done
The while loop
#!/bin/bash
count=1
while [ "$count" -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
$(( ... )) performs arithmetic.
Putting it together
#!/bin/bash
# Report the size of every log file
for file in /var/log/*.log; do
if [ -f "$file" ]; then
size=$(du -h "$file" | cut -f1)
echo "$file -> $size"
fi
done
Try it
- Write a loop that prints
1to10 - Extend it to print only even numbers (hint: test
$((n % 2)) -eq 0) - Write a script that checks whether a directory passed as
$1exists
Advertisement