#!/usr/bin/env bashCommon when Bash may not live at /bin/bash.
Production-minded Bash script patterns for files, arguments, parsing, temp files, logging, retries, and common automation tasks.
Shebangs, argument handling, and reusable script patterns.
#!/usr/bin/env bashCommon when Bash may not live at /bin/bash.
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)Useful for loading sibling files and assets reliably.
while (($#)); do
case "$1" in
-v|--verbose) verbose=1 ;;
-o|--output) output=$2; shift ;;
*) echo "unknown arg: $1" >&2; exit 1 ;;
esac
shift
doneA common pattern for lightweight scripts.
while getopts ':f:o:v' opt; do
case $opt in
f) file=$OPTARG ;;
o) output=$OPTARG ;;
v) verbose=1 ;;
\?) echo "invalid option: -$OPTARG" ;;
esac
doneGood for POSIX-style short flags in shell scripts.
shift $((OPTIND - 1))Leaves only positional arguments in $@.
mktemp, safe file operations, and path helpers.
tmp=$(mktemp)Prefer mktemp over hand-rolled temp names.
tmpdir=$(mktemp -d)Pair with trap cleanup for robust scripts.
cmp -s new.conf current.conf || cp new.conf current.confUseful in deployment and config-management scripts.
if ! command -v jq >/dev/null 2>&1; then echo 'jq required'; exit 1; fiPortable and very common in setup scripts.
dir=$PWD
while [[ $dir != / && ! -d $dir/.git ]]; do dir=$(dirname "$dir"); done
echo "$dir"Useful for repo-aware scripts.
Common script logging patterns.
log() { printf '[%s] %s
' "$(date +%H:%M:%S)" "$*"; }Small helper that makes scripts easier to debug.
warn() { printf 'WARN: %s
' "$*" >&2; }
die() { printf 'ERROR: %s
' "$*" >&2; exit 1; }Keeps scripts readable and consistent.
./deploy.sh 2>&1 | tee deploy.logGreat for CI logs and manual runs.
Common retry, timeout, and parallel patterns.
for attempt in {1..5}; do
curl -sf http://localhost:8080/health && break
sleep 2
doneUseful for service startup and network flakiness.
timeout 30s bash -lc 'long_running_job'Very useful in automation, though timeout is an external command.
job1 &
pid1=$!
job2 &
pid2=$!
wait "$pid1" "$pid2"Useful in CI or local automation when tasks are independent.
user=$(jq -r '.user.name' payload.json)
echo "$user"Prefer jq for structured JSON instead of fragile grep/sed hacks.
cat > app.env <<EOF
APP_ENV=${APP_ENV:-dev}
PORT=${PORT:-3000}
EOFCommon in local setup scripts and container entrypoints.