Overview and What You Will Learn
A production-ready shell script is one that fails loudly, can be re-run safely, never runs twice at once, checks that its own work succeeded and tells the team what happened. The difference between a script that works on your laptop and one you trust against production is mostly error handling, idempotency, locking, retries and logging.
By the end of this lab you will be able to:
- Start every script from a safe template with strict mode, logging and a cleanup trap
- Parse arguments with
getopts, validate them and add a dry-run mode - Write idempotent steps that are safe to run ten times
- Retry flaky operations with exponential backoff and a cap
- Prevent concurrent runs with
flock - Deploy a container with a health check and automatic rollback
- Send Slack notifications and test scripts with
shellcheckandbats
Why This Matters in Production
A deployment script that works on the happy path is easy. The scripts that save you at 2 AM also handle the partial failure: the image pulled but the container did not start, the health check never went green, or a colleague launched the same deploy a minute earlier. On a payments platform in the style of Razorpay or Stripe, a half-finished deploy that nobody was told about is worse than a clean failure. The patterns below turn a list of commands into something you can hand to a pipeline, an on-call engineer or a new teammate.
Core Principles
Every production script follows the same shape: validate first, take a lock, change something, verify the change, then either report success or undo the change and report failure. The flow below is the skeleton that the rest of this lab fills in.
arguments]) --> B[Check tools
and take lock] B --> C[Run deploy steps] C --> D{Health check
passes?} D -->|Yes| E[Notify success] D -->|No| F[Roll back and
notify failure] E --> G([Release lock and exit]) F --> G classDef start fill:#326CE5,color:#FFFFFF classDef step fill:#F1F5F9,color:#1E293B classDef good fill:#10B981,color:#FFFFFF classDef bad fill:#EF4444,color:#FFFFFF class A,G start class B,C,D step class E good class F bad
The script built in this lab is a single deploy.sh. It needs Bash 4.4 or newer, plus docker, curl, jq and flock. Each section below adds one part of the file, in the order it appears in the script.
Detailed Step-by-Step Practical Lab
How to Start a Bash Script with a Safe Template
Strict mode makes the script stop on the first unexpected failure instead of continuing with bad state. set -e exits when a command fails, set -u treats an unset variable as an error, and pipefail makes a pipeline fail if any stage fails. Add a logger, a die helper and a cleanup trap in the same template.
# Defaults, overridable by flags or environmentENVIRONMENT="production"DRY_RUN=falseVERBOSE=falseSERVICE=""VERSION=""REGISTRY="${REGISTRY:-registry.devops.in}"HEALTH_URL="${HEALTH_URL:-http://localhost:4000/health}" SCRIPT_NAME=$(basename "$0")START_TS=$(date +%s) # Logs go to stderr so stdout stays clean for datalog() { printf '%s [%s] %s\n' "$(date -u +%FT%TZ)" "$1" "${*:2}" >&2; }info() { log INFO "$@"; }warn() { log WARN "$@"; }err() { log ERROR "$@"; }debug() { if [[ "$VERBOSE" == true ]]; then log DEBUG "$@"; fi; }die() { err "$@"; exit 1; } # Dry-run wrapper: wrap every command that changes somethingrun_cmd() { if [[ "$DRY_RUN" == true ]]; then info "[DRY RUN] $*" return 0 fi "$@"} require_cmds() { local cmd for cmd in "$@"; do command -v "$cmd" > /dev/null 2>&1 || die "Required command not found: $cmd" done} # Runs on every exit, success or failurecleanup() { local code=$? info "Finished with exit code ${code} after $(( $(date +%s) - START_TS ))s"}The strict-mode line and the traps are registered later, inside main, so that tests can source the file without side effects.
Common MistakeWriting
exit 0inside a function. In Bash,exitends the whole script, not just the function. Usereturn 0orreturn 1inside functions and keepexitfor the top level.
Common MistakeAssuming
set -eprotects code inside a function that is called from anifor after||. Bash switchesset -eoff in those contexts, so a failing command in the middle of the function is silently ignored. Check critical commands explicitly with|| return 1, as the deploy function does below.
How to Parse Command-Line Arguments with getopts
getopts is the standard Bash tool for short options such as -e staging. It handles missing values and unknown flags for you. It does not understand long options like --dry-run, so the function below first translates a few long forms into short ones.
# deploy.sh (part 2): arguments and validation usage() { local code="${1:-1}" cat << EOFUsage: ${SCRIPT_NAME} [OPTIONS] <service> <version> Deploy a containerised service to an environment. Options: -e ENV Target environment: staging or production (default: production) -n Dry run, or --dry-run: print actions without doing them -v Verbose output -h Show this help Examples: ${SCRIPT_NAME} payment-api v1.2.3 ${SCRIPT_NAME} -e staging -n payment-api v1.2.3EOF exit "$code"} parse_args() { local args=() arg opt for arg in "$@"; do case "$arg" in --dry-run) args+=(-n) ;; --help) args+=(-h) ;; *) args+=("$arg") ;; esac done set -- "${args[@]}" OPTIND=1 while getopts ":e:nvh" opt; do case "$opt" in e) ENVIRONMENT="$OPTARG" ;; n) DRY_RUN=true ;; v) VERBOSE=true ;; h) usage 0 ;; :) err "Option -${OPTARG} needs a value"; usage 1 ;; *) err "Unknown option -${OPTARG}"; usage 1 ;; esac done shift $((OPTIND - 1)) [[ $# -eq 2 ]] || { err "service and version are required"; usage 1; } SERVICE="$1" VERSION="$2"} validate_version() { [[ "$1" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; } validate_env() { case "$1" in staging|production) return 0 ;; *) return 1 ;; esac} # Never trust input: these values end up in file paths and docker commandsvalidate_inputs() { validate_env "$ENVIRONMENT" || die "Environment must be staging or production, got: $ENVIRONMENT" validate_version "$VERSION" || die "Version must look like v1.2.3, got: $VERSION" [[ "$SERVICE" =~ ^[a-z][a-z0-9-]*$ ]] || die "Invalid service name: $SERVICE"}TipGive every script that changes something a dry-run mode, and route every changing command through one wrapper such as
run_cmd. The dry run then shows exactly what a real run would do, which makes reviews and new-hire training much easier.
How to Write Idempotent Shell Scripts
An idempotent script leaves the system in the same state whether it runs once or ten times. Check the current state before acting, and prefer commands that are naturally repeatable.
# Not idempotent: adds a duplicate line every runecho 'export PATH=/opt/tools/bin:$PATH' >> ~/.bashrc # Idempotent: single quotes keep $PATH literal, grep -x checks the whole lineline='export PATH=/opt/tools/bin:$PATH'grep -qxF "$line" ~/.bashrc || echo "$line" >> ~/.bashrc # Directories: -p succeeds if it already existsmkdir -p /opt/payment-api/releases # Users: create only if missingid -u payment-svc > /dev/null 2>&1 \ || sudo useradd --system --no-create-home --shell /usr/sbin/nologin payment-svc # Config files: act only if the content changed, and validate before reloadingif ! cmp -s /etc/nginx/sites-available/payment /etc/nginx/conf.d/payment.conf; then sudo install -m 0644 /etc/nginx/sites-available/payment /etc/nginx/conf.d/payment.conf sudo nginx -t sudo systemctl reload nginxfiSwitching a current symlink needs extra care. ln -sf on an existing symlink that points to a directory creates a new link inside that directory instead of replacing the link. Use -n, and rename into place so the switch is atomic:
ln -sfn "/opt/payment-api/releases/${VERSION}" /opt/payment-api/current.tmpmv -T /opt/payment-api/current.tmp /opt/payment-api/currentHow to Add Retry Logic with Exponential Backoff
Retrying handles transient failures such as a registry timeout or a service that is still starting. Exponential backoff doubles the wait after each failure, a cap stops it growing without limit, and a little random jitter stops many scripts retrying in lockstep.
# deploy.sh (part 3): retries and health checks # usage: retry <max_attempts> <initial_delay_s> <description> <command...>retry() { local max_attempts="$1" delay="$2" description="$3" shift 3 local attempt=1 max_delay=60 sleep_for until "$@"; do if (( attempt >= max_attempts )); then err "${description} failed after ${max_attempts} attempts" return 1 fi sleep_for=$(( delay + RANDOM % 3 )) warn "${description} failed (attempt ${attempt}/${max_attempts}), retrying in ${sleep_for}s" sleep "$sleep_for" attempt=$(( attempt + 1 )) delay=$(( delay * 2 )) if (( delay > max_delay )); then delay=$max_delay; fi done info "${description} succeeded on attempt ${attempt}"} # Poll a health endpoint until it answers or the time runs outwait_for_healthy() { local url="$1" max_wait="${2:-60}" interval="${3:-3}" elapsed=0 if [[ "$DRY_RUN" == true ]]; then info "[DRY RUN] would wait for ${url}" return 0 fi info "Waiting for ${url} (up to ${max_wait}s)" while (( elapsed < max_wait )); do if curl --silent --fail --max-time 5 "$url" > /dev/null; then info "Healthy after ${elapsed}s" return 0 fi sleep "$interval" elapsed=$(( elapsed + interval )) done err "Not healthy after ${max_wait}s" return 1}Only retry operations that are safe to repeat. Retrying a read or an image pull is fine, but retrying a payment call needs an idempotency key on the other side.
How to Prevent Concurrent Script Runs with flock
flock takes an exclusive lock on a file. If a second copy of the script starts while the first is running, it fails immediately instead of racing the first one. The kernel releases the lock automatically when the script exits, even after a crash.
# deploy.sh (part 4): locking acquire_lock() { local lock_file="/var/lock/deploy-${SERVICE}.lock" # Open file descriptor 9 on the lock file and hold it for the life of the script exec 9> "$lock_file" flock -n 9 || die "Another deployment of ${SERVICE} is already running" debug "Lock acquired: ${lock_file}"}The user running the script must be able to write to /var/lock (or use /run/lock or another directory they own). To lock a script from the outside instead, run flock -n /var/lock/deploy.lock ./deploy.sh.
How to Deploy a Container with Health Check and Rollback
The deployment records what is running now, replaces it, waits for the health check and, if anything fails, puts the previous version back. Because set -e is ignored inside functions called from if, every step that matters ends with || return 1.
# deploy.sh (part 5): deploy and rollback IMAGE=""PREVIOUS_IMAGE=""REPLACED=false # Image of the container that is running now (empty if none)current_image() { docker inspect --format '{{.Config.Image}}' "$SERVICE" 2> /dev/null || true} start_container() { local image="$1" run_cmd docker run -d \ --name "$SERVICE" \ --restart unless-stopped \ --publish 4000:4000 \ --env-file "/etc/${SERVICE}/env" \ "$image"} deploy() { IMAGE="${REGISTRY}/${SERVICE}:${VERSION}" PREVIOUS_IMAGE=$(current_image) info "Previous image: ${PREVIOUS_IMAGE:-none}" info "Deploying ${IMAGE} to ${ENVIRONMENT}" # Idempotent: already running this version and healthy means nothing to do if [[ "$PREVIOUS_IMAGE" == "$IMAGE" ]] \ && curl --silent --fail --max-time 5 "$HEALTH_URL" > /dev/null 2>&1; then info "${IMAGE} is already deployed and healthy" return 0 fi # Pull first: if this fails, nothing has changed yet retry 3 2 "pull ${IMAGE}" run_cmd docker pull "$IMAGE" || return 1 info "Replacing running container" REPLACED=true run_cmd docker stop --time 30 "$SERVICE" 2> /dev/null || true run_cmd docker rm "$SERVICE" 2> /dev/null || true start_container "$IMAGE" || return 1 wait_for_healthy "$HEALTH_URL" 60 3 || return 1 info "Deployment successful: ${IMAGE}"} rollback() { if [[ "$REPLACED" != true ]]; then info "Nothing was changed, no rollback needed" return 0 fi if [[ -z "$PREVIOUS_IMAGE" ]]; then err "No previous image recorded, manual recovery required" return 1 fi warn "Rolling back to ${PREVIOUS_IMAGE}" run_cmd docker rm --force "$SERVICE" 2> /dev/null || true start_container "$PREVIOUS_IMAGE" || return 1 wait_for_healthy "$HEALTH_URL" 60 3}This pattern stops and replaces one container, so there is a short gap in service. For zero downtime, run the new version beside the old one behind a load balancer and switch traffic after the health check passes; the same validate, verify and roll back structure applies.
How to Send Slack Notifications from a Shell Script
A notification tells the team a deploy finished, failed or was rolled back, without anyone watching a terminal. Build the JSON with jq so quotes and special characters in messages cannot break it, and never let a failed notification fail the deployment.
# deploy.sh (part 6): notifications notify_slack() { local status="$1" message="$2" color payload if [[ "$DRY_RUN" == true ]]; then info "[DRY RUN] would notify Slack: ${status}" return 0 fi if [[ -z "${SLACK_WEBHOOK:-}" ]]; then warn "SLACK_WEBHOOK not set, skipping notification" return 0 fi case "$status" in SUCCESS) color="#10B981" ;; FAILURE) color="#EF4444" ;; ROLLBACK) color="#F97316" ;; *) color="#64748B" ;; esac payload=$(jq -n \ --arg status "$status" \ --arg message "$message" \ --arg color "$color" \ --arg service "$SERVICE" \ --arg version "$VERSION" \ --arg env "$ENVIRONMENT" \ '{ text: ("Deployment " + $status + ": " + $service + " " + $version), attachments: [{ color: $color, fields: [ {title: "Service", value: $service, short: true}, {title: "Version", value: $version, short: true}, {title: "Environment", value: $env, short: true}, {title: "Details", value: $message, short: false} ] }] }') if ! printf '%s' "$payload" | curl --silent --fail --max-time 10 \ --request POST --header 'Content-Type: application/json' \ --data @- "$SLACK_WEBHOOK" > /dev/null; then warn "Slack notification failed" fi return 0}SecurityA Slack webhook URL is a credential. Supply it through the environment from your CI secret store, never hard-code it in the script, and never print it in logs.
How to Put It Together in a main Function
main runs the steps in order. The guard at the bottom runs main only when the file is executed, not when a test sources it, and strict mode and traps are switched on there so they never leak into the test runner.
# deploy.sh (part 7): main main() { trap cleanup EXIT trap 'die "Interrupted"' INT TERM parse_args "$@" validate_inputs require_cmds docker curl jq flock acquire_lock if deploy; then notify_slack SUCCESS "Deployed ${IMAGE}" return 0 fi err "Deployment failed" if rollback; then notify_slack ROLLBACK "Deploy of ${VERSION} failed. Service is running ${PREVIOUS_IMAGE:-the previous state}." else notify_slack FAILURE "Deploy of ${VERSION} failed and rollback also failed. Manual action needed." fi exit 1} # Run only when executed directly, so tests can source this file safelyif [[ "${BASH_SOURCE[0]}" == "$0" ]]; then set -euo pipefail main "$@"fichmod +x deploy.sh # Preview first, then run for real./deploy.sh --dry-run -e staging payment-api v1.2.3./deploy.sh -e staging payment-api v1.2.3How to Lint and Test Shell Scripts with shellcheck and bats
shellcheck is a static analyser that catches the bugs that cause most shell incidents: unquoted variables, masked exit codes and wrong comparisons. bats is a test framework for Bash, so functions like input validation get automated checks.
sudo apt install shellcheck bats # Lint (-x follows sourced files)shellcheck -x deploy.shThe warnings you will see most often:
- SC2086: quote variables to prevent word splitting and globbing. Write
cp "$FILE" /tmp/, notcp $FILE /tmp/ - SC2006: use
$(...)instead of legacy backticks - SC2155: declare and assign separately, because
local out=$(cmd)hides the exit status ofcmd
mkdir -p testcat > test/deploy.bats << 'EOF'#!/usr/bin/env bats setup() { # deploy.sh only runs main when executed, so sourcing it is safe source "${BATS_TEST_DIRNAME}/../deploy.sh"} @test "usage exits with the requested code" { run usage 0 [ "$status" -eq 0 ] run usage 1 [ "$status" -eq 1 ]} @test "validate_version accepts a v-prefixed semver" { run validate_version "v1.2.3" [ "$status" -eq 0 ]} @test "validate_version rejects other formats" { run validate_version "latest" [ "$status" -eq 1 ]} @test "validate_env rejects an unknown environment" { run validate_env "prod-typo" [ "$status" -eq 1 ]} @test "run_cmd prints instead of executing in dry-run mode" { DRY_RUN=true run run_cmd docker rm --force payment-api [ "$status" -eq 0 ] [[ "$output" == *"[DRY RUN]"* ]]}EOF bats test/The helper is named run_cmd on purpose. A function called run would collide with the run command that bats provides. Run both shellcheck and bats in your CI pipeline so a broken script never reaches the server.
Production Best Practices & Common Pitfalls
- Start strict. Use
set -euo pipefail, and know thatset -ehas gaps inside functions called from conditions. - Quote every variable expansion. Unquoted variables are the most common source of shell bugs, and
shellcheckfinds them. - Validate input before using it. Service names and versions end up in paths and commands, so check them against a pattern.
- Make every step idempotent. Check state before acting, and use repeatable commands such as
mkdir -pandln -sfn. - Verify, then trust. A deploy is not done until the health check passes. Ideally the health endpoint also reports the running version.
- Notify on every outcome. Success, rollback and failure messages should all reach the team, and notification failures must not fail the deploy.
- Keep secrets out of logs and arguments. Use environment variables or a secret store, and avoid
set -xaround commands that use secrets.
| Pattern | Wrong | Correct |
|---|---|---|
| Argument parsing | Manual if [ "$1" == "-e" ] |
getopts, plus validation of every value |
| Idempotency | Run and hope | Check state before every change |
| Failed deploy | Exit and leave a half-deployed service | Roll back, notify, release the lock |
| Retries | Fixed sleep, unlimited attempts | Exponential backoff with a cap |
| Concurrency | Two deploys can overlap | flock on a per-service lock file |
| Testing | Manual runs only | shellcheck plus bats in CI |
Remember
set -xprints every command with its expanded variables, so a password or API key stored in a variable will appear in the log. Turn it off withset +xbefore any command that handles secrets.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| Lint a script | shellcheck -x deploy.sh |
| Run tests | bats test/ |
| Dry run | ./deploy.sh --dry-run payment-api v1.2.3 |
| Debug trace | bash -x deploy.sh payment-api v1.2.3 |
| Run under an external lock | flock -n /var/lock/deploy.lock ./deploy.sh payment-api v1.2.3 |
| Check syntax without running | bash -n deploy.sh |
| Test a Slack webhook | curl --fail -X POST -H 'Content-Type: application/json' -d '{"text":"test"}' "$SLACK_WEBHOOK" |
| Show the running image | docker inspect --format '{{.Config.Image}}' payment-api |
| Symptom | Likely cause | Fix |
|---|---|---|
| Script continues after a failure | set -e ignored in an if or ` |
|
unbound variable error |
set -u caught a typo or missing input |
Fix the name, or use ${VAR:-default} |
| Deploy refuses to start | Lock held by another run | Check for a running deploy before removing anything |
| Pipeline error hidden | Missing pipefail |
Add set -o pipefail |
| Symlink ends up inside the target | ln -sf on a directory link |
Use ln -sfn and mv -T |
Tests fail on exit |
Test sourced a script that ran main |
Add the BASH_SOURCE guard |