Bash isn't just commands — it's a full (if quirky) programming language. Variables, conditionals and loops turn a sequence of commands into automation. The syntax is unusual, so watch the spacing carefully; it's the #1 source of beginner errors.
Variables
Assign with name=value — no spaces around the =. Read the value with a $ prefix, and quote it to be safe:
name="Aanya" # no spaces around =greeting="Hello, $name"echo "$greeting" # Hello, Aanya — always quote variablescount=5echo "You have $count messages"
Command substitution
Capture a command's output into a variable with $(…):
today=$(date +%Y-%m-%d)files=$(ls | wc -l)echo "On $today there are $files files"
Conditionals
if tests a condition inside [ … ]. Note the specific operators — Bash uses words for numbers and symbols for files:
if [ "$count" -gt 3 ]; thenecho "More than three"elif [ "$count" -eq 0 ]; thenecho "None"elseecho "A few"fi# File testsif [ -f "config.txt" ]; then echo "file exists"; fiif [ -d "logs" ]; then echo "directory exists"; fi
| Test | True when |
|---|---|
-eq -ne -gt -lt | Numeric equal / not / greater / less |
= != | String equal / not equal |
-f file | File exists |
-d dir | Directory exists |
-z str | String is empty |
Loops
# Loop over filesfor file in *.txt; doecho "Processing $file"done# Loop over a listfor env in dev staging prod; doecho "Deploying to $env"done# While loopcount=1while [ "$count" -le 3 ]; doecho "Attempt $count"count=$((count + 1)) # arithmeticdone
Practice
Write commands (not yet a script) that: store today's date in a variable, loop over every .txt file in a folder and print its name, and use an if to print "backup exists" only when a backup/ directory is present.
Key takeaways
- 01Assign variables with name=value (no spaces); read with $name and always quote "$var".
- 02Capture command output with $(command).
- 03if uses [ … ] with word operators for numbers (-gt, -eq) and -f/-d for files.
- 04for loops iterate files or lists; while loops run until a condition is false.
- 05Spacing and quoting are the top sources of Bash bugs — be precise.
