Shell Scripting Patterns for DevOps
Write reliable shell scripts: strict mode, argument parsing, functions, logging, and safe file operations.
Shell scripts are everywhere in DevOps:
- setup scripts
- deployment hooks
- cron/systemd jobs
- CI steps
- quick maintenance tasks
Most production “script bugs” are caused by:
- missing error checks
- unquoted variables (whitespace/globbing bugs)
- silent failures in pipelines
- unclear logging
This tutorial shows hardened patterns you can copy.
Learning outcomes
You’ll learn:
- strict mode and safer Bash defaults
- how to structure scripts with functions
- how to handle arguments and usage
- safe cleanup and temporary files
1) Start with strict mode
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
What each option does:
-e: exit on command failure-u: treat unset variables as errorspipefail: pipeline fails if any command fails
2) Add logging helpers
log() { echo "[INFO] $*" >&2; }
warn() { echo "[WARN] $*" >&2; }
err() { echo "[ERROR] $*" >&2; }
Use:
log "Starting backup"
3) Validate inputs early
Pattern:
- show usage
- exit non-zero on bad args
usage() {
cat >&2 <<'EOF'
Usage:
backup.sh <source_dir> <dest_dir>
EOF
}
if [[ $# -ne 2 ]]; then
usage
exit 2
fi
src="$1"
dst="$2"
4) Use functions to isolate steps
ensure_dir() {
local dir="$1"
mkdir -p "$dir"
}
copy_tree() {
local src="$1" dst="$2"
cp -a "$src" "$dst"
}
5) Safe file operations
Always quote variables:
cp -a "$src" "$dst"
rm -rf -- "$path"
-- prevents paths starting with - from being treated like flags.
6) Temporary files + cleanup
tmp="$(mktemp)"
cleanup() { rm -f "$tmp"; }
trap cleanup EXIT
# ... use $tmp
7) Example: copy with checks
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
log() { echo "[INFO] $*" >&2; }
usage() {
cat >&2 <<'EOF'
Usage:
copy-safe.sh <source> <destination>
EOF
}
if [[ $# -ne 2 ]]; then
usage
exit 2
fi
src="$1"
dst="$2"
if [[ ! -e "$src" ]]; then
log "Source not found: $src"
exit 1
fi
log "Copying $src -> $dst"
mkdir -p "$(dirname "$dst")"
cp -a "$src" "$dst"
log "Done"
Next steps
This completes your “Linux + automation” foundation. Next DevOps pages:
- Git & GitHub workflows
- GitHub Actions CI/CD
- Terraform (IaC) basics
- Ansible (idempotent configuration)
- Jenkins pipelines
- Monitoring & observability mindset
Frequently Asked Questions
What is shell strict mode?
Strict mode makes errors fail fast: `set -euo pipefail` stops on non-zero exit codes, undefined variables, and failed pipeline commands. It prevents a lot of “silent failure” bugs.
Why log to stderr?
So normal output can remain clean for piping/command substitution, while errors go to logs/terminals consistently.