Variables, Conditionals & Loops

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · Bash

Variables, Conditionals & Loops

Beginner ⭐ 50 XP ⏱ 20 min #bash#control-flow

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: -z empty, -n non-empty, ==, !=
  • Numeric tests: -eq -ne -lt -le -gt -ge
  • File tests: -f file exists, -d dir exists, -e exists, -r/-w/-x
  • Loops: for x in list, while [[ cond ]], and case for 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
  1. Loop over all .txt files in a directory and print each name and size.
  2. Write an if that checks whether a number argument is greater than 100.
  3. Convert a chain of if/elif into a case statement.
  4. Use a while loop to read a file line by line.
🧾Cheat Sheet
ConstructSyntax
Ifif [[ cond ]]; then … fi
Else ifelif [[ cond ]]; then
Forfor x in a b c; do … done
Whilewhile [[ cond ]]; do … done
Casecase $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