Bash Scripting Cheat Sheet: Variables, Tests & Loops
Bash syntax for variables, conditionals, loops, and safe scripting in one place.
The bash constructs you reach for when writing CI and automation scripts.
Strict mode & variables
script.sh
#!/usr/bin/env bash
set -euo pipefail
name="${1:-default}" # default if unset
count=${#array[@]} # array length
echo "${PATH%%:*}" # first path entryParameter expansion
| Form | Result |
|---|---|
| ${var:-x} | x if var unset/empty |
| ${var:=x} | Assign x if unset |
| ${var:?msg} | Error msg if unset |
| ${var#pat} | Strip shortest prefix |
| ${var%pat} | Strip shortest suffix |
| ${var/old/new} | Replace first match |
| ${#var} | String length |
Test conditions
| Test | True when |
|---|---|
| [[ -f f ]] | File exists |
| [[ -d d ]] | Directory exists |
| [[ -z s ]] | String empty |
| [[ -n s ]] | String non-empty |
| [[ a == b ]] | String equal |
| (( a > b )) | Arithmetic compare |
Loops
loops
for f in *.txt; do echo "$f"; done
while read -r line; do echo "$line"; done < file
case "$x" in
start) run ;;
*) echo "unknown" ;;
esacKey takeaways
- set -euo pipefail catches errors, unset vars, and broken pipes.
- Always quote "${var}" to survive spaces and globbing.
- [[ ]] is the safer modern test; (( )) for arithmetic.
Related guides
sed & awk Cheat Sheet: Text Processing One-LinersA sed and awk cheat sheet - substitution, deletion, field extraction, and the one-liners that power text proc…
Exit Codes Cheat Sheet: Shell Status Codes ExplainedAn exit codes cheat sheet - what 0, 1, 2, 126, 127, 130, and signal-derived codes mean, and how to read $? in…
Unix Signals Cheat Sheet: SIGTERM, SIGKILL & HandlersA Unix signals cheat sheet - SIGTERM, SIGKILL, SIGINT, SIGHUP, default actions, and trapping signals for grac…