Bash · Cheat sheet
Bash scripting cheat sheet
The complete Bash reference, beginner to advanced: script safety, variables and expansion, conditionals, loops, functions, arrays, string manipulation, parameter expansion, process substitution, and traps/debugging — with example output.
Script basics & safetyBeginner
#!/usr/bin/env bash
Shebang — pick bash from PATH.
set -euo pipefail
Exit on error, unset var, or any pipe failure.
IFS=$'\n\t'
Safer word-splitting (newline/tab only).
chmod +x script.sh && ./script.sh
Make executable and run.
bash -n script.sh
Syntax-check without executing.
bash -x script.sh
Trace every command as it runs.
+ name=prod + echo prod prod
Variables & expansionBeginner
name="prod"
Assign — no spaces around =.
echo "$name"
Always quote expansions to avoid splitting.
out=$(date +%F)
Command substitution into a variable.
2025-06-12
readonly PI=3.14
Constant — cannot be reassigned.
export PATH="$HOME/bin:$PATH"
Export to child processes.
echo "${name:-default}"
Use default if name is unset/empty.
echo "${name:?must be set}"
Error out with a message if unset.
echo $((3 + 4 * 2))
Integer arithmetic.
11
ConditionalsIntermediate
if [[ -f "$f" ]]; then ...; fi
File exists and is a regular file.
[[ -d dir ]]
Directory exists.
[[ -z "$s" ]] / [[ -n "$s" ]]
String is empty / non-empty.
[[ "$a" == "$b" ]]
String equality (use = or ==).
[[ "$n" -gt 10 ]]
Numeric: -eq -ne -lt -le -gt -ge.
[[ "$s" =~ ^v[0-9]+ ]]
Regex match inside [[ ]].
case "$x" in a) ..;; *) ..;; esac
Multi-way branch on a value.
LoopsIntermediate
for f in *.log; do gzip "$f"; done
Loop over glob matches.
for i in {1..5}; do echo "$i"; done
Brace-expansion range.
1 2 3 4 5
for ((i=0;i<n;i++)); do ...; done
C-style counting loop.
while read -r line; do ...; done < file
Read a file line by line, safely.
until [[ done ]]; do ...; done
Loop until the condition becomes true.
break / continue
Exit a loop / skip to the next iteration.
FunctionsIntermediate
greet() { echo "hi $1"; }
Define a function; $1 is the first arg.
greet world
Call it with arguments.
hi world
local x=1
Function-scoped variable.
return 2
Exit status of a function (0–255).
result=$(compute)
Capture a function’s stdout.
echo "$@" / "$#"
All args as words / the arg count.
Strings & parameter expansionAdvanced
${#s}
Length of a string.
${s:2:4}
Substring: offset 2, length 4.
${s^^} / ${s,,}
Upper-case / lower-case the whole string.
PROD / prod
${file%.txt}
Strip a suffix (shortest match with %).
${path##*/}
Basename — strip longest leading match.
app.js # from /srv/app.js
${path%/*}
Dirname — strip the trailing /file.
${s/foo/bar}
Replace first foo (// replaces all).
${arr[@]:1:2}
Slice an array from index 1, length 2.
ArraysAdvanced
arr=(a b c)
Index array literal.
echo "${arr[1]}"
Element by index (0-based).
b
echo "${arr[@]}"
All elements as separate words.
echo "${#arr[@]}"
Number of elements.
arr+=(d)
Append an element.
declare -A m; m[key]=val
Associative array (map).
for k in "${!m[@]}"; do ...; done
Iterate map keys.
Redirection & process substitutionAdvanced
cmd > out.log 2>&1
Send stdout and stderr to a file.
cmd 2>/dev/null
Discard errors.
cmd >> out.log
Append instead of overwrite.
diff <(sort a) <(sort b)
Feed command output as a file (process sub).
cat <<EOF > file
...
EOF
Here-doc — multi-line literal into a file.
cmd | tee -a out.log
Print to screen and append to a file.
exec 3>&1
Open a custom file descriptor.
Traps & debuggingAdvanced
trap "rm -f $tmp" EXIT
Run cleanup whenever the script exits.
trap 'echo "err on line $LINENO"' ERR
Report the line an error occurred on.
tmp=$(mktemp)
Create a safe temporary file.
PS4='+ ${BASH_SOURCE}:${LINENO}: '
Richer trace prefix for set -x.
set -x / set +x
Turn command tracing on / off around a block.
declare -p var
Print a variable’s type and value for debugging.
shellcheck script.sh
Static analysis — catches quoting and logic bugs.
Go deeper
Full, hands-on DevSecOps courses