Bash Shell Scripting Cheat Sheet — Syntax, Conditionals & Loops
Practical syntax reference for Bash scripts, conditional flags (-f, -d, -z), loops, variables, exit codes, and string manipulation.
Script Headers & Conditionals
#!/usr/bin/env bash
set -euo pipefail
Strict Bash header: exits immediately on error, unset variable, or failed pipeline
if [[ -f "$FILE" ]]; then ... fi
Check if file exists and is a regular file
if [[ -z "$VAR" ]]; then ... fi
Check if string variable is empty or unset (-n checks non-empty)
if [[ "$EXIT_CODE" -eq 0 ]]; then
Numeric comparison: -eq (equal), -ne (not equal), -gt (greater), -lt (less)
Special Variables & Loops
$? / $# / $@
$? = exit code of last command, $# = arg count, $@ = all arguments array
for file in *.png; do ... done
Iterate over file glob matches in current directory
OUTPUT=$(curl -s https://api.example.com)
Command substitution: capture command stdout into variable