Overview and What You Will Learn
A production shell script is a script that fails loudly, can be run twice safely, never runs twice at once, verifies its own result, and tells the team what happened. The gap between "works on my machine" and "safe to run against production" is made of argument handling, idempotency, locking, retries, health checks, rollback, and notifications.
By the end of this lab you will:
- Parse flags with
getoptsand print a useful--help-style usage message - Add a real dry-run mode that wraps every side effect
- Write idempotent steps that are safe to repeat
- Prevent concurrent runs with
flock - Retry flaky operations with capped exponential backoff
- Deploy a container with a health check and automatic rollback to the previous image
- Send Slack notifications without leaking secrets
- Lint with
shellcheckand test withbats
Why This Matters in Production
Most deployment incidents are not caused by the happy path. They come from a half-finished run, two engineers deploying at once, a network blip during an image pull, or a bad release that nobody noticed because nothing verified it. A script that handles those cases turns a 2 AM page into a Slack message that says "rolled back automatically".
Teams that deploy many times a day, such as those at Stripe and Spotify, treat deployment scripts as production code: reviewed, linted, tested, and written so a failed run leaves the system in a known state.
Core Principles
Every production script follows the same shape: validate first, take the lock, change things, verify, then either report success or undo the change and report failure.
arguments] --> B[Check required
commands] B --> C[Acquire lock
with flock] C --> D[Run deploy steps] D --> E{Health check
passes?} E -->|Yes| F([Notify success]) E -->|No| G[Roll back to
previous image] G --> H([Notify failure]) classDef prep fill:#326CE5,color:#ffffff classDef act fill:#8B5CF6,color:#ffffff classDef decide fill:#DBEAFE,color:#1E293B classDef good fill:#10B981,color:#ffffff classDef bad fill:#EF4444,color:#ffffff class A,B,C prep class D act class E decide class F good class G,H bad
These strict-mode options catch most silent failures:
| Setting | Effect |
|---|---|
set -e |
Exit when a command fails |
set -u |
Treat an unset variable as an error |
set -o pipefail |
A pipeline fails if any stage fails |
set -E |
Let trap ... ERR fire inside functions |
Remember
set -ehas blind spots: it is ignored inifconditions,&&and||lists, and the left side of a pipeline. Check results explicitly for steps that matter, and useif cmd; thenrather than relying on automatic exit.
Detailed Step-by-Step Practical Lab
All milestones build one script, deploy.sh. Keep each function in the same file in the order shown.
Milestone 1: How to Parse Arguments with getopts and Validate Input
Parse flags into variables, then validate everything before the script touches the system. A -h request is not an error, so it exits 0.
readonly SCRIPT_NAME="$(basename "$0")"readonly APP_PORT=4000 ENVIRONMENT="production"REGION="ap-south-1"DRY_RUN=falseVERBOSE=falseSERVICE=""VERSION="" usage() { cat << EOFUsage: ${SCRIPT_NAME} [OPTIONS] <service> <version> Deploy a service to a target environment. Options: -e ENV Target environment (default: production) -r REGION AWS region (default: ap-south-1) -d Dry run: print actions without performing them -v Verbose output -h Show this help Examples: ${SCRIPT_NAME} payment-api v1.2.3 ${SCRIPT_NAME} -e staging -d payment-api v1.2.3EOF} log() { printf '%s [%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" "${*:2}" >&2; }info() { log INFO "$@"; }warn() { log WARN "$@"; }err() { log ERROR "$@"; }die() { err "$@"; exit 1; } validate_version() { [[ "$1" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]} parse_args() { local opt local OPTIND=1 while getopts "e:r:dvh" opt; do case "$opt" in e) ENVIRONMENT="$OPTARG" ;; r) REGION="$OPTARG" ;; d) DRY_RUN=true ;; v) VERBOSE=true ;; h) usage; exit 0 ;; *) usage >&2; exit 2 ;; esac done shift $((OPTIND - 1)) [[ $# -eq 2 ]] || { usage >&2; die "service and version are required"; } SERVICE="$1" VERSION="$2" validate_version "$VERSION" || die "version must look like v1.2.3, got: $VERSION" [[ "$ENVIRONMENT" =~ ^(production|staging|dev)$ ]] || die "unknown environment: $ENVIRONMENT"} require_cmd() { local cmd for cmd in "$@"; do command -v "$cmd" > /dev/null 2>&1 || die "required command not found: $cmd" done}Common MistakeWriting
[[ "$VERBOSE" == true ]] && echo ...as a standalone line. When the test is false the line returns non-zero and, if it is the last command in a function, can tripset -e. Useif [[ ... ]]; then ...; fi.
Milestone 2: How to Add a Dry-Run Mode That Covers Every Side Effect
Route every command that changes state through one wrapper. In dry-run mode it prints the command instead of running it, so the output is an exact preview of the real run.
run_cmd() { if [[ "$DRY_RUN" == true ]]; then info "[DRY RUN] $*" return 0 fi "$@"}Read-only commands, such as docker inspect, run normally in both modes so the preview reflects real state.
TipA dry run is only trustworthy if nothing bypasses
run_cmd. When you add a new step, ask "does this change anything?" and wrap it if the answer is yes.
Milestone 3: How to Write Idempotent Steps
An idempotent step gives the same end state whether it runs once or ten times. Check the current state before acting, or use commands that are naturally repeatable.
mkdir -p "/opt/${SERVICE}" # Users: create only if missingif ! getent passwd payment-svc > /dev/null; then run_cmd useradd --system --no-create-home --shell /usr/sbin/nologin payment-svcfi # Config lines: append only if absent (single quotes keep $PATH literal)if ! grep -qxF 'export PATH=/usr/local/bin:$PATH' ~/.bashrc; then echo 'export PATH=/usr/local/bin:$PATH' >> ~/.bashrcfi # Config files: copy and reload only when content changedif ! cmp -s /etc/nginx/sites-available/payment /etc/nginx/sites-enabled/payment; then run_cmd sudo cp /etc/nginx/sites-available/payment /etc/nginx/sites-enabled/payment run_cmd sudo nginx -t run_cmd sudo systemctl reload nginxfiTo switch a release symlink atomically, create a temporary link and rename it over the old one. Readers never see a missing or half-written link:
switch_release() { local link="/opt/${SERVICE}/current" run_cmd ln -sfn "/opt/${SERVICE}/${VERSION}" "${link}.tmp" run_cmd mv -Tf "${link}.tmp" "$link"}Milestone 4: How to Prevent Concurrent Runs with flock
Two deployments of the same service at once can corrupt shared state. Take an exclusive lock on a file descriptor inside the script. The lock is released automatically when the script exits, even after a crash.
acquire_lock() { local lock_file="${LOCK_DIR:-/var/lock}/deploy-${SERVICE}.lock" exec 9> "$lock_file" || die "cannot open lock file: $lock_file" flock -n 9 || die "another deployment of ${SERVICE} is already running" info "acquired lock: $lock_file"}Remember
flock -nfails immediately instead of waiting. Useflock -w 60if you would rather queue for up to a minute. Run the script as a user that can write to the lock directory.
Milestone 5: How to Retry with Capped Exponential Backoff
Retry only operations that are safe to repeat, such as image pulls and health checks, and cap both the attempts and the delay.
retry() { local max_attempts="$1" delay="$2" description="$3" shift 3 local attempt=1 while true; do if "$@"; then info "${description} succeeded on attempt ${attempt}" return 0 fi if (( attempt >= max_attempts )); then err "${description} failed after ${max_attempts} attempts" return 1 fi warn "${description} failed (attempt ${attempt}/${max_attempts}), retrying in ${delay}s" sleep "$delay" attempt=$((attempt + 1)) delay=$(( delay * 2 > 30 ? 30 : delay * 2 )) done} wait_for_healthy() { local url="$1" max_wait="${2:-60}" interval="${3:-3}" elapsed=0 info "waiting for ${url} to become healthy" while (( elapsed < max_wait )); do if curl -fsS --max-time 3 "$url" > /dev/null 2>&1; then info "healthy after ${elapsed}s" return 0 fi sleep "$interval" elapsed=$((elapsed + interval)) done err "not healthy after ${max_wait}s" return 1}Using attempt=$((attempt + 1)) instead of ((attempt++)) avoids a classic set -e trap, because ((x++)) returns status 1 when the old value was 0.
Milestone 6: How to Deploy with a Health Check and Automatic Rollback
Record what is running before you change anything. If the new version is not healthy, restart the previous image, not just the previous symlink, because the running container is what serves traffic.
PREVIOUS_IMAGE="" start_container() { local image="$1" run_cmd docker run -d \ --name "$SERVICE" \ --restart unless-stopped \ -p "127.0.0.1:${APP_PORT}:${APP_PORT}" \ --env-file "/etc/${SERVICE}/env" \ "$image"} stop_container() { run_cmd docker stop --time 30 "$SERVICE" 2> /dev/null || true run_cmd docker rm "$SERVICE" 2> /dev/null || true} deploy() { local image="${SERVICE}:${VERSION}" PREVIOUS_IMAGE="$(docker inspect --format '{{.Config.Image}}' "$SERVICE" 2> /dev/null || true)" info "previous image: ${PREVIOUS_IMAGE:-none}" info "deploying: ${image} to ${ENVIRONMENT} (${REGION})" retry 5 2 "pull ${image}" run_cmd docker pull "$image" || return 1 stop_container start_container "$image" || return 1 if [[ "$DRY_RUN" == false ]]; then wait_for_healthy "http://127.0.0.1:${APP_PORT}/health" 60 3 || return 1 fi switch_release info "deployment successful: ${image}"} rollback() { if [[ -z "$PREVIOUS_IMAGE" ]]; then err "no previous image to roll back to" return 1 fi warn "rolling back to ${PREVIOUS_IMAGE}" stop_container start_container "$PREVIOUS_IMAGE" wait_for_healthy "http://127.0.0.1:${APP_PORT}/health" 60 3}This pattern stops the old container before starting the new one, so there is a short gap in service. For zero-downtime releases use a rolling update behind a load balancer, or start the new container on a second port and switch the proxy once it is healthy.
SecurityThe env file holds secrets. Keep it at mode 600 or 640 owned by the service account, pass it with
--env-filerather than-e KEY=value(which appears inpsoutput and shell history), and never print it.
Milestone 7: How to Send Slack Notifications from a Script
Build the JSON with jq so quotes and newlines in messages cannot break the payload. Read the webhook URL from the environment, and treat a failed notification as a warning, never as a failed deployment.
notify_slack() { local status="$1" message="$2" local webhook="${SLACK_WEBHOOK:-}" if [[ -z "$webhook" || "$DRY_RUN" == true ]]; then info "slack notification skipped (${status})" return 0 fi local color case "$status" in SUCCESS) color="#36a64f" ;; FAILURE) color="#ff0000" ;; ROLLBACK) color="#ff9900" ;; *) color="#808080" ;; esac local payload payload="$(jq -n \ --arg status "$status" --arg message "$message" --arg color "$color" \ --arg service "$SERVICE" --arg version "$VERSION" --arg env "$ENVIRONMENT" \ '{attachments: [{ color: $color, title: ("Deployment " + $status), fields: [ {title: "Service", value: $service, short: true}, {title: "Version", value: $version, short: true}, {title: "Environment", value: $env, short: true}, {title: "Message", value: $message, short: false} ]}]}')" curl -fsS --max-time 10 -X POST "$webhook" \ -H 'Content-Type: application/json' \ -d "$payload" > /dev/null \ || warn "slack notification failed"}Milestone 8: How to Wire It Together with a main Function
Wrapping the entry point in a guard lets tests source the file without running a deployment. Strict mode is enabled inside the guard so it does not leak into the test runner.
main() { parse_args "$@" require_cmd docker curl jq flock acquire_lock if deploy; then notify_slack SUCCESS "${SERVICE} ${VERSION} deployed" return 0 fi err "deployment failed" if rollback; then notify_slack ROLLBACK "${SERVICE} rolled back to ${PREVIOUS_IMAGE}" else notify_slack FAILURE "${SERVICE} ${VERSION} failed and rollback did not complete" fi return 1} if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then set -Eeuo pipefail main "$@"fiPreview a run first, then run it for real:
./deploy.sh -d -e staging payment-api v1.2.3./deploy.sh -e staging payment-api v1.2.3Milestone 9: How to Lint with shellcheck and Test with bats
shellcheck finds quoting bugs, unsafe patterns, and portability problems before they reach production. bats runs small test cases against the functions you sourced.
sudo apt install shellcheck bats shellcheck -x deploy.sh# SC2086: Double quote to prevent globbing and word splitting# Bad: cp $FILE /tmp/# Good: cp "$FILE" /tmp/# SC2006: Use $(...) instead of backticksmkdir -p testcat > test/deploy.bats << 'EOF'#!/usr/bin/env bats setup() { source "${BATS_TEST_DIRNAME}/../deploy.sh" sleep() { :; } # make retry tests instant COUNTER_FILE="$(mktemp)" echo 0 > "$COUNTER_FILE"} teardown() { rm -f "$COUNTER_FILE"} flaky_twice() { local n; n="$(cat "$COUNTER_FILE")" echo $((n + 1)) > "$COUNTER_FILE" [ "$n" -ge 2 ]} @test "validate_version accepts semantic versions" { run validate_version "v1.2.3" [ "$status" -eq 0 ]} @test "validate_version rejects free text" { run validate_version "latest" [ "$status" -ne 0 ]} @test "run_cmd only prints in dry-run mode" { DRY_RUN=true run run_cmd touch /tmp/should-not-exist [ "$status" -eq 0 ] [ ! -e /tmp/should-not-exist ]} @test "retry succeeds after transient failures" { run retry 5 1 "flaky step" flaky_twice [ "$status" -eq 0 ]} @test "retry gives up after max attempts" { run retry 2 1 "always failing" false [ "$status" -eq 1 ]} @test "rollback fails cleanly with no previous image" { PREVIOUS_IMAGE="" run rollback [ "$status" -eq 1 ]}EOF bats test/deploy.batsRun both in CI so a lint warning or failing test blocks the merge.
Production Best Practices & Common Pitfalls
Write scripts so the safe behavior is the default and the dangerous behavior needs an explicit flag.
- Validate all input and required commands before changing anything.
- Route every state change through
run_cmdso dry-run is trustworthy. - Take a
flocklock for any script that must not overlap with itself. - Verify the result with a health check and roll back automatically on failure.
- Log to stderr with timestamps, and never log secrets.
- Lint with
shellcheckand test the logic withbatsin CI. - Prefer a configuration tool such as Ansible, or an orchestrator, once a script outgrows a few hundred lines.
| Mistake | Problem | Fix |
|---|---|---|
exit inside a function |
Terminates the whole script, skips rollback | Use return, and exit only at the top level |
| Unquoted variables | Word splitting and globbing bugs | Quote every expansion: "$VAR" |
set -x around secrets |
Values appear in logs | Disable tracing before using secrets |
| Rolling back only a symlink | Container keeps running the bad image | Restart the previous image |
Fixed sleep for readiness |
Races on slow starts | Poll a health endpoint with a timeout |
| Notification failure aborts deploy | Healthy release reported as failed | Treat notifications as best effort |
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| Lint a script | shellcheck -x deploy.sh |
| Run tests | bats test/ |
| Preview a deploy | ./deploy.sh -d -e staging SERVICE VERSION |
| Trace execution | bash -x deploy.sh -d SERVICE VERSION |
| Run with an external lock | flock -n /var/lock/deploy.lock ./deploy.sh SERVICE VERSION |
| Test a webhook | curl -fsS -X POST -H 'Content-Type: application/json' -d '{"text":"test"}' "$SLACK_WEBHOOK" |
| Symptom | First command | What to look for |
|---|---|---|
| Script exits with no message | bash -x deploy.sh |
The last command traced before exit |
| "another deployment is running" | lsof /var/lock/deploy-SERVICE.lock |
A live process holding the lock |
| Health check never passes | docker logs SERVICE --tail 50 |
Startup errors or a wrong port |
| Rollback did not start | docker ps -a |
Previous container removed, image tag missing |
| Slack message not sent | curl -v -X POST "$SLACK_WEBHOOK" -d '{"text":"test"}' |
HTTP status and body from Slack |
TipMake dry-run the habit. Run
-dfirst in every environment, read the printed plan, then run for real. It also makes the script a self-documenting runbook for new team members.
RememberUse
exitonly at the top level of a script andreturninside functions. A strayexitin a helper ends the whole script and skips your rollback and notifications.
Security
set -xprints every command with its expanded variables, so a password or API key in a variable appears in the logs. Turn tracing off withset +xbefore commands that use secrets, and keep webhook URLs and tokens in the environment or a secrets manager, not in the script.
Common MistakeTesting only the happy path. Force a failure on purpose, for example a bad image tag or a health endpoint that returns 500, and confirm the script rolls back and notifies. A rollback you have never run is a rollback you cannot trust.