Bash Scripting Cheat Sheet
Complete Bash scripting reference — variables, expansions, conditionals, loops, functions, arrays, and error handling patterns.
Variables & Expansion
| VAR="value" | Assign variable (no spaces around =) |
| echo "$VAR" | Expand variable (always quote to avoid word split) |
| readonly VAR | Make variable immutable |
| export VAR | Export to child processes |
| ${VAR:-default} | Use default if unset or empty |
| ${VAR:=default} | Assign default if unset; also expands to default |
| ${VAR:?error msg} | Exit with error if unset or empty |
| ${#VAR} | Length of string value |
| $1 $2 ... $@ $# $0 | Positional args, all args, arg count, script name |
| $? $$ $! | Exit code, current PID, last background PID |
| result=$(command) | Command substitution — capture output |
| $(( 2 + 3 )) | Arithmetic expansion |
Conditionals
if [[ condition ]]; then ... elif [[ other ]]; then ... else ... fi
| Test | Meaning |
|---|---|
| -f file | File exists and is regular file |
| -d dir | Directory exists |
| -z "$VAR" | String is empty |
| -n "$VAR" | String is not empty |
| "$a" == "$b" | String equality (use [[ ]] not [ ]) |
| $a -eq $b / -ne / -lt / -le / -gt / -ge | Numeric comparisons |
| [[ "$s" =~ regex ]] | Regex match (result in BASH_REMATCH) |
Loops
| for i in a b c; do ... done | Iterate over list |
| for i in {1..10}; do ... done | Brace expansion range |
| for ((i=0; i<10; i++)); do ... done | C-style for loop |
| for f in *.txt; do ... done | Glob over files |
| while [[ condition ]]; do ... done | While loop |
| while IFS= read -r line; do ... done < file | Read file line by line (safe, handles spaces) |
| break / continue | Exit loop / skip to next iteration |
Functions
my_func() {
local arg1="$1" # local variable
echo "Processing: $arg1"
return 0 # exit code (not value)
}
my_func "hello" # call function
echo $? # check exit code
| local VAR="val" | Function-scoped variable (always use local!) |
| return 0 / return 1 | Return exit code (0=success, 1=failure) |
| result=$(my_func) | Capture stdout output of function |
Arrays
| arr=(a b c) | Declare array |
| ${arr[0]} | Access element by index |
| ${arr[@]} | All elements (safely quoted) |
| ${#arr[@]} | Array length |
| arr+=("new") | Append element |
| for item in "${arr[@]}"; do | Iterate array (always quote!) |
| declare -A map; map[key]="val" | Associative array (hash map) |
String Operations
| ${VAR#prefix} | Remove shortest prefix match |
| ${VAR##prefix} | Remove longest prefix match (greedy) |
| ${VAR%suffix} | Remove shortest suffix match |
| ${VAR%%suffix} | Remove longest suffix match (greedy) |
| ${VAR/old/new} | Replace first occurrence |
| ${VAR//old/new} | Replace all occurrences |
| ${VAR:2:5} | Substring: offset 2, length 5 |
| ${VAR^^} / ${VAR,,} | Uppercase / lowercase (Bash 4+) |