Bash · Cheat sheet
Bash scripting cheat sheet
Bash scripting cheat sheet: safety flags, variables, loops, functions, arrays, parameter expansion, and traps.
Script basics & safety
Beginner#!/usr/bin/env bash- Shebang — pick bash from PATH.
set -euo pipefail- Exit on most errors, unset vars, pipe failures (-e is off in if/&&/|| tests).
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.Example output
+ name=prod + echo prod prod
Variables & expansion
Beginnername="prod"- Assign — no spaces around =.
echo "$name"- Always quote expansions to avoid splitting.
out=$(date +%F)- Command substitution into a variable.Example output
2025-06-12
out=${ date +%F; }- Bash 5.3+: substitution that runs in the current shell (no subshell), so side effects persist.
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 or empty.
echo $((3 + 4 * 2))- Integer arithmetic.Example output
11
Conditionals
Intermediateif [[ -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.
Loops
Intermediatefor f in *.log; do gzip "$f"; done- Loop over glob matches.
for i in {1..5}; do echo "$i"; done- Brace-expansion range.Example output
1 2 3 4 5
for ((i=0;i<n;i++)); do ...; done- C-style counting loop.
while IFS= read -r line; do ...; done < file- Read a file line by line, keeping leading/trailing spaces.
until [[ -f ready.flag ]]; do sleep 1; done- Loop until the condition becomes true.
break / continue- Exit a loop / skip to the next iteration.
Functions
Intermediategreet() { echo "hi $1"; }- Define a function; $1 is the first arg.
greet world- Call it with arguments.Example output
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 expansion
Advanced${#s}- Length of a string.
${s:2:4}- Substring: offset 2, length 4.
${s^^} / ${s,,}- Upper-case / lower-case the whole string.Example output
PROD / prod
${file%.txt}- Strip a suffix (shortest match with %).
${path##*/}- Basename — strip longest leading match.Example output
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.
Arrays
Advancedarr=(a b c)- Index array literal.
echo "${arr[1]}"- Element by index (0-based).Example output
b
echo "${arr[@]}"- All elements as separate words.
echo "${#arr[@]}"- Number of elements.
arr+=(d)- Append an element.
mapfile -t lines < file- Read every line of a file into an array (-t drops newlines).
declare -A m; m[key]=val- Associative array (map).
for k in "${!m[@]}"; do ...; done- Iterate map keys.
Redirection & process substitution
Advancedcmd > 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 & debugging
Advancedtrap 'rm -f "$tmp"' EXIT- Run cleanup whenever the script exits.
trap 'echo "err on line $LINENO"' ERR- Report the line an error occurred on (set -E to cover functions).
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.
Related
- Cheat sheetLinux command cheat sheet
- Cheat sheetPython for DevSecOps cheat sheet
- Interview guideLinux interview questions
- CourseBash for ops, done safely
- CourseAdvanced scripting for DevSecOps
- CourseLinux essentials
- Field noteBash strict mode: writing ops scripts that fail loudly
- Field noteSandboxing Linux services with systemd security directives
- Field noteLinux capabilities: dropping root the right way
Primary references
Found a technical issue on this page? Report it with the tool version you used and the behavior you saw. How resources are maintained.
Go deeper
Hands-on courses for Bash