Overview and What You Will Learn
A reliable Bash script stops at the first real error, validates its inputs, quotes every variable, cleans up after itself and leaves a log. The gap between a fragile script and a dependable one is rarely cleverness. It is a small set of habits applied every time. In this lab, you will build one release script, deploy-demo.sh, in six milestones, then run it three ways: a normal release, a release that fails its health check and rolls back, and two releases started at once.
- Starting a script with a safe shebang, strict mode and a logging helper
- Using variables, arrays, default values and parameter expansion with correct quoting
- Writing conditionals with
[[ ]]for strings, files and numbers - Looping over arrays and retrying with a counter
- Building functions with
localvariables and meaningful exit codes - Cleaning up and rolling back with
trap, and preventing concurrent runs withflock
Why This Matters in Production
Every DevOps engineer eventually owns a shell script that runs in production. At a company like Shopify, a deploy script that ignores a failed step can leave a service half-deployed, with the old version stopped, the new one broken, and no rollback. A script that checks its work, rolls back on failure and always cleans up either finishes the job or puts everything back, and that is the difference between a quiet night and a page.
Core Principles
Strict mode makes failures loud. With set -Eeuo pipefail, the script exits when a command fails, when it reads an unset variable, or when any command in a pipeline fails. A trap on EXIT then runs on every way out of the script, so cleanup and failure alerts cannot be skipped.
ERR trap logs line] N --> F([Last command done]) E --> T[EXIT trap
cleanup and alert] F --> T classDef start fill:#D1FAE5,color:#1E293B classDef dec fill:#F97316,color:#FFFFFF classDef bad fill:#EF4444,color:#FFFFFF classDef good fill:#326CE5,color:#FFFFFF class S,F start class Q dec class E bad class N,T good
The most common source of Bash bugs is unquoted variables, because the shell splits an unquoted value on whitespace and expands wildcards in it:
FILENAME="my report final.txt" Unquoted, wrong: cp $FILENAME /tmp/ the shell runs cp my report final.txt /tmp/ and copies three files, or fails Quoted, correct: cp "$FILENAME" /tmp/ the shell runs cp "my report final.txt" /tmp/ and copies exactly one fileAlways write "$VAR" and "${ARRAY[@]}". The double-bracket test [[ ]] is safer than [ ] because it does not word-split its operands, and it adds glob and regex matching.
Detailed Step-by-Step Practical Lab
This lab needs Bash 4 or later and a Linux system with flock, which is part of util-linux. It deploys to a temporary directory and simulates the hosts, so it is safe to run anywhere. The script is built by appending to one file, so run the milestones in order.
Milestone 1 - Script Structure, Strict Mode and Logging
Create the file with a shebang, strict mode and a logging function:
cat > deploy-demo.sh << 'EOF'#!/usr/bin/env bash # Usage: ./deploy-demo.sh <version> # -E lets the ERR trap work inside functions, -e exits on error,# -u fails on unset variables, pipefail fails a pipeline if any part failsset -Eeuo pipefail SCRIPT_NAME=$(basename "$0")readonly SCRIPT_NAMELOG_DIR="${LOG_DIR:-/tmp/deploy-demo-logs}"mkdir -p "$LOG_DIR"LOG_FILE="$LOG_DIR/deploy-$(date +%Y%m%d-%H%M%S).log"readonly LOG_FILE log() { local level="$1" shift echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*" | tee -a "$LOG_FILE"} usage() { echo "Usage: $SCRIPT_NAME <version>" >&2 echo " version: release tag such as v1.2.3" >&2 exit 1} if [[ $# -lt 1 ]]; then usagefiEOFchmod +x deploy-demo.shNotice that SCRIPT_NAME is assigned first and made readonly on the next line. Writing readonly VAR=$(command) in one step hides the command's exit status from set -e.
Milestone 2 - Variables, Arrays and Parameter Expansion
cat >> deploy-demo.sh << 'EOF' TAG="$1"APP_NAME="payment-api"ENVIRONMENT="${DEPLOY_ENV:-staging}" # default if unset or emptyDEPLOY_ROOT="${DEPLOY_ROOT:-/tmp/deploy-demo}"SERVERS=("mumbai-prod-node-1" "mumbai-prod-node-2" "mumbai-prod-node-3") : "${TAG:?TAG must be set}" # exit with a message if empty # Parameter expansion trims strings without calling external toolsVERSION_NUMBER="${TAG#v}" # v1.2.3 becomes 1.2.3MAJOR="${VERSION_NUMBER%%.*}" # 1.2.3 becomes 1 RELEASE_DIR="$DEPLOY_ROOT/$APP_NAME/releases/$TAG"CURRENT_LINK="$DEPLOY_ROOT/$APP_NAME/current"EOFAssignments have no spaces around =. The ${VAR:-default} form supplies a default, and ${VAR:?message} makes a missing value a fatal, readable error.
Milestone 3 - Conditionals with [[ ]]
cat >> deploy-demo.sh << 'EOF' check_dependencies() { local missing=() local dep for dep in flock readlink df; do if ! command -v "$dep" > /dev/null 2>&1; then missing+=("$dep") fi done if [[ ${#missing[@]} -gt 0 ]]; then log ERROR "Missing dependencies: ${missing[*]}" return 1 fi} validate_input() { # regex match: the tag must look like v1.2.3 if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then log ERROR "Version must look like v1.2.3, got: $TAG" return 1 fi # combine tests with && and || if [[ "$ENVIRONMENT" != "staging" && "$ENVIRONMENT" != "production" ]]; then log ERROR "DEPLOY_ENV must be staging or production, got: $ENVIRONMENT" return 1 fi # file test if [[ -d "$RELEASE_DIR" ]]; then log ERROR "Release $TAG is already deployed" return 1 fi # numeric test: at least 1 MB free local free_kb free_kb=$(df --output=avail -k "$DEPLOY_ROOT" | tail -n 1 | tr -d ' ') if [[ $free_kb -lt 1024 ]]; then log ERROR "Not enough free disk space: ${free_kb} KB" return 1 fi log INFO "Input validated: $TAG for $ENVIRONMENT (major version $MAJOR)"}EOFMilestone 4 - Loops
cat >> deploy-demo.sh << 'EOF' deploy_to_hosts() { local server for server in "${SERVERS[@]}"; do log INFO "Deploying $TAG to $server" # A real script would run: ssh -n "$server" "sudo systemctl restart $APP_NAME" sleep 1 done} wait_for_healthy() { local attempt for ((attempt = 1; attempt <= 5; attempt++)); do if health_check; then log INFO "Healthy after $attempt attempt(s)" return 0 fi log WARN "Not healthy yet (attempt $attempt of 5)" sleep "$attempt" done return 1}EOFThe array loop quotes "${SERVERS[@]}" so each element stays one word. When you loop over a command's output, use while IFS= read -r line; do ... done < <(command). If you call ssh inside such a loop, use ssh -n, or it will swallow the rest of the loop's input.
Milestone 5 - Functions, Return Codes and Rollback
cat >> deploy-demo.sh << 'EOF' # Stand-in for a real health endpoint check. FAIL_HEALTH=1 simulates a bad release.health_check() { [[ "${FAIL_HEALTH:-0}" != "1" && -f "$CURRENT_LINK/VERSION" ]]} previous_release() { if [[ -L "$CURRENT_LINK" ]]; then readlink "$CURRENT_LINK" fi} switch_release() { local target="$1" ln -sfn "$target" "$CURRENT_LINK" log INFO "current now points to $target"} rollback() { local previous="$1" if [[ -n "$previous" && -d "$previous" ]]; then log WARN "Rolling back to $previous" switch_release "$previous" else log WARN "No previous release to roll back to" fi} deploy_release() { local previous previous=$(previous_release) mkdir -p "$RELEASE_DIR" echo "$TAG" > "$RELEASE_DIR/VERSION" switch_release "$RELEASE_DIR" deploy_to_hosts if ! wait_for_healthy; then log ERROR "Health check failed for $TAG" rollback "$previous" rm -rf "$RELEASE_DIR" return 1 fi}EOFFunctions return an exit status, not a value. Use return 0 or return 1 for success and failure, and echo plus command substitution, as previous_release does, to hand back text. Declare variables with local, and assign command output on a separate line from local, because local x=$(cmd) also hides the command's status.
Milestone 6 - Traps, Locking and the Main Flow
cat >> deploy-demo.sh << 'EOF' TEMP_DIR="" notify() { local message="$1" # skip quietly when no webhook is configured if [[ -z "${SLACK_WEBHOOK:-}" ]]; then return 0 fi curl -s -X POST "$SLACK_WEBHOOK" \ -H 'Content-type: application/json' \ --data-raw "$(jq -n --arg text "$message" '{text: $text}')" \ > /dev/null || true} cleanup() { local exit_code=$? if [[ -n "$TEMP_DIR" && -d "$TEMP_DIR" ]]; then rm -rf "$TEMP_DIR" fi if [[ $exit_code -ne 0 ]]; then log ERROR "Deployment of $TAG FAILED (exit code $exit_code)" notify "Deployment failed: $APP_NAME $TAG" else log INFO "Deployment of $TAG SUCCEEDED" fi} on_error() { log ERROR "Command failed at line $1"} # Register traps early, before anything that needs cleaning uptrap 'on_error $LINENO' ERRtrap cleanup EXITtrap 'log WARN "Interrupted"; exit 130' INT TERM acquire_lock() { # file descriptor 9 holds the lock until the script exits, even after a crash exec 9> "/tmp/${SCRIPT_NAME}.lock" if ! flock -n 9; then log ERROR "Another deployment is already running" exit 1 fi} main() { check_dependencies acquire_lock mkdir -p "$DEPLOY_ROOT/$APP_NAME/releases" TEMP_DIR=$(mktemp -d) log INFO "Starting $APP_NAME $TAG (working in $TEMP_DIR)" validate_input deploy_release} mainEOFMilestone 7 - Check, Run and Break It
Check the syntax and lint the script, then run a normal release twice with different versions:
bash -n deploy-demo.shshellcheck deploy-demo.sh ./deploy-demo.sh v1.0.0./deploy-demo.sh v1.1.0readlink /tmp/deploy-demo/payment-api/currentThe link should point to the v1.1.0 release directory. Now simulate a bad release. The health check fails, the script rolls back to v1.1.0, removes the failed release, and exits non-zero:
FAIL_HEALTH=1 ./deploy-demo.sh v1.2.0echo "exit code: $?"readlink /tmp/deploy-demo/payment-api/currentStart two releases at the same time. The second one hits the lock and refuses to run:
./deploy-demo.sh v1.3.0 &sleep 0.5./deploy-demo.sh v1.4.0waitTrace a run line by line with bash -x, which is the quickest way to see what the shell actually does:
bash -x ./deploy-demo.sh v1.5.0 2>&1 | head -n 40Clean up:
rm -rf /tmp/deploy-demo /tmp/deploy-demo-logs deploy-demo.shProduction Best Practices & Common Pitfalls
Common MistakeWriting
((count++))in a script withset -e. Whencountis 0, the expression evaluates to 0, which counts as failure, and the script exits on a perfectly good line. Usecount=$((count + 1))instead.
TipRun
shellcheck script.shbefore committing any shell script. It flags unquoted variables, masked return values, bad comparisons and unreachable code, with an explanation and a fix for each.
Remember
trap cleanup EXITruns however the script ends: normal completion,exit 1, a failure caught byset -e, or a signal. Register it before you create anything that needs cleaning up, and read$?on the first line of the handler.
SecurityNever pass external input to
eval. It executes whatever text it receives, so a crafted value becomes arbitrary code. Use arrays, parameter expansion or explicit parsing instead, and quote every expansion that touches user input.
- Know where
set -edoes not fire. It is ignored in the condition of anif, in&&and||lists, and inside command substitutions assigned withlocal. Check the results of commands that matter explicitly. - Expect
grepto exit 1 when nothing matches. Withpipefail, a harmless no-match can end the script, so writegrep pattern file || truewhen no match is acceptable. - Prefer
[[ ]]but validate numbers. An empty variable in[[ $COUNT -eq 0 ]]evaluates as 0 and is silently true, so test[[ -n "$COUNT" ]]first or use${COUNT:-0}. - Do not assume Bash 4 everywhere. Features such as
${var^^}need Bash 4, and macOS ships Bash 3.2, so declare your minimum version and check it. - Use
flockinstead of a lock file you create and delete. Atouchandrmlock is racy and survives a crash, while anflocklock disappears when the process does. - Write logs to a path the user can write to. Writing to
/var/logfails for non-root users, so default to a user or temp directory and let an environment variable override it.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| Strict mode | set -Eeuo pipefail |
| Trace execution | bash -x script.sh |
| Check syntax only | bash -n script.sh |
| Lint a script | shellcheck script.sh |
| Register cleanup | trap cleanup EXIT |
| Log the failing line | trap 'on_error $LINENO' ERR |
| Default value | ${VAR:-default} |
| Require a variable | ${VAR:?error message} |
| Remove prefix or suffix | ${VAR#prefix} and ${VAR%suffix} |
| Run one instance only | flock -n 9 |
| Problem | Cause | Fix |
|---|---|---|
unbound variable error |
set -u met an unset variable |
Use ${VAR:-} or set a default |
| Script exits with no message | set -e hit a failing command |
Add an ERR trap and run bash -x |
| Filenames with spaces break | Unquoted variable | Quote it as "$VAR" |
unary operator expected |
Empty variable inside [ ] |
Use [[ ]] and quote the variable |
| Cleanup did not run | Trap registered after the failure, or killed with SIGKILL |
Register the trap first, and avoid kill -9 |
flock: command not found |
Not on Linux or util-linux missing | Install util-linux or use a mkdir lock |