Variables, Conditionals & Loops
Add logic to scripts with tests, if/case branches, and for/while loops.
Theory
Logic in Bash is built from tests and loops. The modern test syntax is
[[ ... ]] (safer than the older [ ... ]). Tests return an exit code, which
if, while, and &&/|| use to decide flow.
- String tests:
-zempty,-nnon-empty,==,!= - Numeric tests:
-eq -ne -lt -le -gt -ge - File tests:
-ffile exists,-ddir exists,-eexists,-r/-w/-x - Loops:
for x in list,while [[ cond ]], andcasefor multi-branch
Real-World Example
#!/usr/bin/env bash
for file in *.log; do
if [[ -f "$file" && -s "$file" ]]; then # exists and non-empty
lines=$(wc -l < "$file")
echo "$file has $lines lines"
fi
done
count=0
while [[ $count -lt 3 ]]; do
echo "tick $count"
((count++))
done
case "$1" in
start) echo "starting" ;;
stop) echo "stopping" ;;
*) echo "usage: $0 {start|stop}" ;;
esac Hands-On Exercise
- Loop over all
.txtfiles in a directory and print each name and size. - Write an
ifthat checks whether a number argument is greater than 100. - Convert a chain of
if/elifinto acasestatement. - Use a
whileloop to read a file line by line.
Cheat Sheet▾
| Construct | Syntax |
|---|---|
| If | if [[ cond ]]; then … fi |
| Else if | elif [[ cond ]]; then |
| For | for x in a b c; do … done |
| While | while [[ cond ]]; do … done |
| Case | case $x in a) … ;; esac |
| String empty / non-empty | -z / -n |
| Numeric compare | -eq -lt -gt … |
| File exists / non-empty | -f / -s |
Common Interview Questions▾
What's the difference between -eq and == in Bash tests?
-eq compares integers numerically; == compares strings. Using == on numbers
can give wrong results because “10” sorts before “9” as text.
Why prefer [[ ]] over [ ] ?
[[ ]] is a Bash keyword with safer parsing — it handles empty variables, supports
&&/|| and pattern matching, and avoids many quoting pitfalls of the old [ ].
Official Documentation
📝 My notes on this topic
Auto-saves as you type