Bash Script Examples: Copy-Paste Patterns for Real Scripts
A cheat sheet of tested bash patterns for the jobs scripts do most, from strict mode and argument parsing to cleanup traps and capped parallel jobs.
Checked against the official docs on Oct 24, 2026.

These bash script examples cover what most scripts actually do: fail safely, parse flags, test files and strings, loop over files and lines, slice strings, use arrays, clean up temp files and run jobs in parallel. Every snippet is complete, runs as written in a current Bash 5 release, and is ready to copy.
Bash cheat sheet at a glance
Example results use p=/var/log/app.log.gz and s=Hello.
| Task | Syntax | Example result |
|---|---|---|
| Default if unset or empty | ${PORT:-8080} |
8080 when PORT is unset |
| Stop if unset or empty | ${DEPLOY_ENV:?not set} |
Prints the message and exits |
| String length | ${#p} |
19 |
| File name | ${p##*/} |
app.log.gz |
| Directory | ${p%/*} |
/var/log |
| Drop last extension | ${p%.*} |
/var/log/app.log |
| Drop all extensions | ${p%%.*} |
/var/log/app |
| Replace first or all | ${s/l/L} and ${s//l/L} |
HeLlo and HeLLo |
| Upper or lower case | ${s^^} and ${s,,} |
HELLO and hello |
| Substring | ${s:0:2} and ${s: -3} |
He and llo |
| Is a regular file | [[ -f $f ]] |
True for files, false for directories |
| Is a directory | [[ -d $d ]] |
True for directories |
| Empty string | [[ -z $s ]] |
True when s has length zero |
| Regex match | [[ $s =~ ^v([0-9]+) ]] |
Groups land in BASH_REMATCH |
| Integer compare | (( n >= 10 )) |
Exit status 0 when true |
| Read a file line by line | while IFS= read -r line |
Keeps spaces and backslashes |
| File into an array | mapfile -t lines < file |
One element per line |
| Array length | ${#arr[@]} |
Number of elements |
| Run on exit | trap cleanup EXIT |
Runs even after an error |
| Status of each pipe stage | ${PIPESTATUS[@]} |
One exit code per command |
The detailed behavior of each expansion is in the Parameter Expansion section of the bash(1) manual page. The sections below turn these one-liners into working scripts.
A safe script header
Start scripts with a strict header so mistakes stop the script instead of silently continuing:
#!/usr/bin/env bash
set -euo pipefail
usage() {
printf 'Usage: %s FILE...\n' "${0##*/}" >&2
}
main() {
if (( $# == 0 )); then
usage
exit 2
fi
for file in "$@"; do
printf 'Processing %s\n' "$file"
done
}
main "$@"What each option does, per the Set builtin documentation:
-eexits when a pipeline, list or compound command returns a non-zero status. It's deliberately ignored in the test of anif, afterwhileoruntil, in every part of a&&or||list except the last, and for commands negated with!.-utreats unset variables as an error during expansion, except$@and$*.-o pipefailmakes a pipeline return the status of the last command that failed, instead of only the status of the final command. It's off by default.
A common gotcha is a && shortcut as the last line of a function. (( verbose )) && echo "debug" returns 1 when verbose is 0, so the function returns 1, and under -e the caller then exits. Use a full if statement instead.
Quoting rules that prevent most bugs
Most broken bash scripts break on file names with spaces. A few habits prevent nearly all of it:
- Quote every expansion:
"$file","${files[@]}","$(command)". Unquoted, Bash splits the result into separate words, and glob characters such as*inside it can expand to file names. - Pass arguments through with
"$@". Quoted, it expands each positional parameter to a separate word."$*"joins them into one word, separated by the first character ofIFS. - Use
$(...)for command substitution. The manual lists the backtick form as deprecated, and$(...)nests cleanly.
#!/usr/bin/env bash
set -euo pipefail
show_args() {
printf 'got %d args:' "$#"
printf ' [%s]' "$@"
printf '\n'
}
set -- "one two" three
show_args "$@" # got 2 args: [one two] [three]
show_args $@ # got 3 args: [one] [two] [three]
show_args "$*" # got 1 args: [one two three]Parse flags and arguments with getopts
getopts is the built-in way to handle short options. A leading colon in the option string turns on silent error reporting, so your script prints its own messages:
#!/usr/bin/env bash
set -euo pipefail
verbose=0
output=""
usage() {
printf 'Usage: %s [-v] [-o FILE] INPUT...\n' "${0##*/}" >&2
exit 2
}
while getopts ':vo:h' opt; do
case $opt in
v) verbose=1 ;;
o) output=$OPTARG ;;
h) usage ;;
:) printf 'Option -%s needs a value\n' "$OPTARG" >&2; usage ;;
\?) printf 'Unknown option -%s\n' "$OPTARG" >&2; usage ;;
esac
done
shift "$((OPTIND - 1))"
if (( $# == 0 )); then
usage
fi
if [[ -n $output ]]; then
exec > "$output" # send everything after this line to the file
fi
for input in "$@"; do
if (( verbose )); then
printf 'Reading %s\n' "$input" >&2
fi
wc -l -- "$input"
doneHow it works: o: means -o takes a value, which arrives in OPTARG. In silent mode, an unknown option sets opt to ? and a missing value sets it to :, with the offending letter in OPTARG. After the loop, OPTIND points at the first non-option argument, so shift leaves only the inputs in $@. exec > "$output" redirects the rest of the script's standard output only when -o was given.
Test files, strings and numbers
Inside [[ ]], Bash doesn't word-split or glob variables, so [[ -f $file ]] is safe even when the name has spaces. The full list of operators is on the Bash Conditional Expressions page.
#!/usr/bin/env bash
set -euo pipefail
file=${1:-config.ini}
if [[ ! -e $file ]]; then
printf 'Missing: %s\n' "$file" >&2
exit 1
elif [[ -d $file ]]; then
printf '%s is a directory\n' "$file" >&2
exit 1
fi
if [[ -s $file && -r $file ]]; then
echo "readable and not empty"
fi
tag="v5.3.0"
if [[ $tag =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
echo "major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]} patch=${BASH_REMATCH[3]}"
fi
count=$(wc -l < "$file")
if (( count > 100 )); then
echo "large file: $count lines"
fi
case ${file##*.} in
ini|conf) echo "config file" ;;
json) echo "JSON file" ;;
*) echo "other file" ;;
esacThree rules to remember: == on the right side of [[ ]] is a glob pattern unless you quote it, =~ uses POSIX extended regular expressions, and < or > inside [[ ]] compare strings, not numbers. For numbers, use (( )), which returns status 0 when the expression is non-zero.
Loop over files, lines and ranges
#!/usr/bin/env bash
set -euo pipefail
shopt -s nullglob
# Every .log file in a directory (nullglob: zero matches means zero iterations)
for f in ./logs/*.log; do
printf '%s: %s lines\n' "$f" "$(wc -l < "$f")"
done
# A file line by line, skipping blanks and comments
while IFS= read -r line; do
[[ -z $line || $line == \#* ]] && continue
printf 'host: %s\n' "$line"
done < hosts.txt
# CSV fields (simple CSV without quoted commas)
while IFS=, read -r name email; do
printf '%s <%s>\n' "$name" "$email"
done < users.csv
# Any file name, even with newlines, from find
while IFS= read -r -d '' path; do
printf 'temp file: %s\n' "$path"
done < <(find . -type f -name '*.tmp' -print0)
# Ranges
for i in {1..3}; do echo "brace $i"; done
for ((i = 0; i < 6; i += 2)); do echo "step $i"; doneWhy these details matter:
IFS=keeps leading and trailing spaces, and-rstopsreadfrom treating backslashes as escapes.- Without
nullglob, a pattern with no matches stays as the literal text./logs/*.log, and the loop runs once on a file that doesn't exist. read -d ''splits on NUL characters, which pairs withfind -print0for file names that contain spaces or newlines.done < <(...)is process substitution. Pipingfindintowhilewould run the loop in a subshell, and variables set inside it would vanish afterward.
Ask for confirmation
Interactive scripts often need a yes or no before doing something destructive. read -p prints a prompt, and -t gives up if no input arrives within that many seconds:
#!/usr/bin/env bash
set -euo pipefail
answer=""
read -r -t 30 -p "Delete old backups? [y/N] " answer || true
case ${answer,,} in
y|yes) echo "Deleting..." ;;
*) echo "Cancelled."; exit 1 ;;
esacThe || true matters under set -e: read returns a non-zero status on a timeout or end of input, which would otherwise end the script before the case runs. ${answer,,} lowercases the reply, so Y, yes and YES all count, and an empty answer falls through to the safe default.
Slice and transform strings
Parameter expansion handles most string work without calling sed, basename or tr:
#!/usr/bin/env bash
set -euo pipefail
path="/var/log/nginx/access.log.gz"
echo "${path##*/}" # access.log.gz
echo "${path%/*}" # /var/log/nginx
echo "${path%.gz}" # /var/log/nginx/access.log
echo "${path%%.*}" # /var/log/nginx/access
title="release notes for bash"
echo "${title^}" # Release notes for bash
echo "${title^^}" # RELEASE NOTES FOR BASH
echo "${title// /-}" # release-notes-for-bash
echo "${#title}" # 22
echo "${title:0:7}" # release
echo "${title: -4}" # bash
port=${PORT:-8080}
echo "port=$port"
: "${DEPLOY_ENV:=staging}"
echo "env=$DEPLOY_ENV"# and % remove the shortest match from the start or end, while ## and %% remove the longest. Note the space in ${title: -4}: without it, Bash reads :- as the default-value operator. := assigns the default to the variable as well as expanding it, and :? stops the script with an error if the variable is unset or empty.
Arrays and associative arrays
#!/usr/bin/env bash
set -euo pipefail
files=(report.csv "monthly summary.pdf" notes.txt)
files+=(extra.log)
echo "count: ${#files[@]}"
for f in "${files[@]}"; do
printf '[%s]\n' "$f"
done
printf 'alpha\nbeta\ngamma\n' > words.txt
mapfile -t words < words.txt
echo "first=${words[0]} last=${words[-1]}"
declare -A ports=([http]=80 [https]=443 [ssh]=22)
ports[dns]=53
for name in "${!ports[@]}"; do
printf '%s=%s\n' "$name" "${ports[$name]}"
doneAlways quote "${files[@]}": quoted, each element stays one word even if it contains spaces. ${!ports[@]} lists the keys, and associative arrays don't keep insertion order, so sort the keys if order matters. mapfile -t strips the trailing newline from each line.
Functions, logging and retries
#!/usr/bin/env bash
set -euo pipefail
log() {
printf '%(%Y-%m-%dT%H:%M:%S)T [%s] %s\n' -1 "$1" "${*:2}" >&2
}
retry() {
local attempts=$1 delay=$2 n
shift 2
for ((n = 1; n <= attempts; n++)); do
if "$@"; then
return 0
fi
log WARN "attempt $n of $attempts failed: $*"
if (( n < attempts )); then
sleep "$delay"
fi
done
return 1
}
if retry 3 2 curl -fsS -o /dev/null https://www.gnu.org/software/bash/; then
log INFO "site is up"
else
log ERROR "giving up"
exit 1
filocal keeps variables inside the function. Functions return a numeric exit status, not a string; to get data out, print it and capture it with result=$(my_function), or write into a named variable with printf -v. The %(...)T format is built into Bash's printf, and -1 means the current time, so logging needs no call to date.
Cleanup traps and error messages
#!/usr/bin/env bash
set -Eeuo pipefail
workdir=$(mktemp -d)
cleanup() {
rm -rf -- "$workdir"
}
trap cleanup EXIT
trap 'printf "error on line %s: %s\n" "$LINENO" "$BASH_COMMAND" >&2' ERR
printf 'data\n' > "$workdir/input.txt"
grep -q data "$workdir/input.txt"
echo "work done in $workdir"The EXIT trap runs when the script exits, including when set -e stops it, so the temp directory doesn't leak. The ERR trap runs when a command fails, and BASH_COMMAND holds the command that was executing at the time. The extra -E option makes functions, command substitutions and subshells inherit the ERR trap, which they otherwise don't.
Run jobs in parallel
#!/usr/bin/env bash
set -euo pipefail
shopt -s nullglob
max_jobs=4
failed=0
for f in ./logs/*.log; do
while (( $(jobs -rp | wc -l) >= max_jobs )); do
wait -n || failed=$((failed + 1))
done
gzip -k -- "$f" &
done
# Collect the rest: wait -n -p leaves the variable unset when no jobs are left
while true; do
unset finished_pid
rc=0
wait -n -p finished_pid || rc=$?
if [[ -z ${finished_pid-} ]]; then
break
fi
if (( rc != 0 )); then
failed=$((failed + 1))
fi
done
printf '%d job(s) failed\n' "$failed"& starts each gzip in the background and jobs -rp lists the process IDs of running jobs, which caps the pool at four. wait -n waits for whichever job finishes next and returns its exit status, and catching that status with || keeps one failed job from stopping the whole script under set -e. The final loop uses wait -n -p, which stores the finished job's process ID and leaves the variable unset once there's nothing left to wait for. That's a safer stop signal than the exit code, because a job can exit with 127 too. If your Bash rejects -p, it's an older release; check echo "$BASH_VERSION" before reworking the script.
Common mistakes and their fixes
These are the bugs that show up again and again in shell scripts, each with the version that works:
- Looping over
$(ls).for f in $(ls *.txt)splits names with spaces into pieces. Loop over the glob directly withfor f in ./*.txt, and turn onnullglobso an empty directory means zero iterations. - Piping into
while read.cat file | while read -r lineruns the loop in a subshell, so a counter you update inside it is back to its old value afterward. Redirect the file into the loop withdone < file, or usedone < <(command)for command output. - Unquoted tests with single brackets.
[ $var == "x" ]fails with "unary operator expected" whenvaris empty, because the variable disappears from the command. Use[[ $var == x ]], or quote the variable in single-bracket tests. - Comparing numbers as strings. Inside
[[ ]],>compares text, so[[ 10 > 9 ]]is false because "1" sorts before "9". Use(( 10 > 9 ))or-gt. - Unchecked
cd. Withoutset -e,cd "$dir"; rm -rf ./*deletes files in the current directory ifcdfails. Writecd "$dir" || exit 1before anything destructive. - Bash syntax under
sh. Arrays,[[ ]]and${var^^}are Bash features. If the shebang says#!/bin/shand/bin/shisn't Bash on that system, the script fails. Use#!/usr/bin/env bashor#!/bin/bash. - Forgetting
local. Variables assigned inside a function are global unless declared withlocal, so a helper can silently overwrite a variable its caller relies on.
Debug a script
- Check syntax without running anything:
bash -n script.sh. - Trace every command as it runs:
bash -x script.sh, or putset -xandset +xaround the part you care about. - Make the trace show where each line came from: the shell prints
PS4before each traced command, so setPS4='+ ${BASH_SOURCE}:${LINENO}: 'before tracing. - Print exit codes of every stage of a pipeline right after it runs:
echo "${PIPESTATUS[@]}".
Before a script has to run under plain sh, check the GNU manual's Major Differences From The Bourne Shell page: it lists Bash-only features such as [[ ]], mapfile, local, the ERR trap and the extra read and wait options used above. More copy-paste references live in the cheat sheets topic.
Quick answers
Should every bash script start with set -euo pipefail?
It's a good default for scripts that should stop on errors, but know its exceptions: -e is ignored inside if tests, while conditions and all but the last command of && or || lists.
What is the difference between [ ] and [[ ]] in bash?
[[ ]] is a bash keyword that skips word splitting and globbing on variables and supports pattern matching with == and regex with =~. The single bracket is the POSIX test command and needs careful quoting.
How do I see which command failed in a bash script?
Add an ERR trap that prints $BASH_COMMAND and $LINENO, or run the script with bash -x to print each command before it executes.
How can I check a bash script for syntax errors without running it?
Run bash -n script.sh. The -n option reads commands without executing them, so it reports syntax errors safely.
Next guide