Most shell scripts start as a quick fix and end up running in production for years. A few habits make the difference between a script that fails safely and one that quietly does the wrong thing.
1. Start every script in strict mode
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
-estops on the first failing command.-utreats unset variables as errors.-o pipefailmakes a pipeline fail if any part of it fails.
2. Quote every variable
Unquoted variables split on spaces and expand wildcards. rm -rf $DIR/* with an empty $DIR is a very bad day. Write "$DIR" every time.
3. Log what you’re doing
log() { printf '%s [%s] %s\n' "$(date -Is)" "${0##*/}" "$*" >&2; }
log "Starting backup of $SOURCE"
4. Clean up with a trap
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
5. Run ShellCheck
ShellCheck catches most quoting and logic mistakes before they reach a server. Add it to your CI pipeline and let it nag you.



