Bash Hour 6: Automation in Practice — Ops Scripts and Cloud CLIs

Apply the Bash mechanisms from the first five hours to real ops tasks: calling HTTP APIs, driving az / aws, parallel bulk operations, rollback-capable deployments, backups with rotation, scheduled runs and CI, then bring them together in opsctl v0.3
Bash 5.3curl 8.23.0Azure CLI 2.93.0AWS CLI 2.40.4jq 1.8.2GNU parallel 20261022Zero cost by defaultVerified against official sources · 2026-11-17
Overall learning goals
  • Use curl to write “production-grade” API calls: distinguish transport failures from HTTP failures (--fail-with-body,-w '%{http_code}'), set connect / total timeouts, retry correctly with exponential backoff (including Retry-After), and paginate by Link header.
  • Treat az and aws as “commands that return JSON” and script them: --query (JMESPath),-o tsv / --output text and jq division of labor, avoiding pitfalls with pagers, colors, interactive prompts and locale defaults (all read-only, zero-cost examples; cloud parts optional).
  • Safely bulk and parallel operations on multiple hosts: xargs -P, GNU parallel,ssh -n -o BatchMode=yes loops, collecting the exit code and output of each host.
  • Write a rollback-capable deployment script: releases/<timestamp> + current symlink, atomic switchover (rename(2)), health-check failure triggers automatic rollback, and old releases are cleaned up.
  • Write a backup and rotation script: temp file plus atomic rename, checksums, rotation by count or age,flock guard against concurrent runs.
  • Choose and configure scheduled runs (cron vs. systemd timers), and in GitHub Actions / GitLab CI , run the same script.
  • Finish the course project opsctl v0.3: add health <url>,backup <dir> and deploy as three subcommands (lib/cmd_health.sh , etc.).

Hour 6 time allocation

#TimeModuleCore contentAnimation / interactionLab
0Before classPreparation: cloud account (optional) and API sandboxStart the local mock API (mockapi.py) and confirm opsctl is at the Lesson 4 v0.2.0, optionally sign in to az / awsEnvironment self-check checklistStart the sandbox and self-check
100–06Calling HTTP APIs: curl, status codes, retries and pagination-f / --fail-with-body,-w, timeouts,--retry family,Retry-After,Link pagination,--jsonCore animation (part 1): API calls with retries and backoffRetries and pagination against the mock API
206–13Scripting cloud CLIs: --query, --output and jq for az and awsJMESPath,-o tsv / --output text,jq -r, pagers and auto-pagination, errors and exit codesInteractive demo: “same JSON, three ways to query it”Offline JSON exercise + optional read-only cloud queries
313–21Bulk operations: parallel execution and SSH loopsxargs -P, GNU parallel (--joblog,--tag), SSH loop’s -n,BatchMode options ConnectTimeoutConcurrency timeline simulatorCheck the hosts in servers.csv in parallel
421–28Deploy scripts: health checks, rollback and atomic switchoverreleases/ + current symlink,ln -sfn + mv -T, health checks, auto-rollback, cleanupCore animation (part 2): atomic switchover and rollbackDeploy 3 versions locally and trigger a rollback
528–35Backup and rotation scriptstar + timestamp, temp file + atomic rename, sha256, rotation by count / age, flock, restore drillRotation window visualizationBack up ~/bashlab/data and verify the restore
635–42Scheduled runs: cron and systemd timerscrontab syntax and environment pitfalls,OnCalendar,Persistent,RandomizedDelaySec, user-level timerscron vs. timer comparison timelineRun backups with a user-level systemd timer
742–50Running scripts in CI: GitHub Actions / GitLab CIBash defaults in CI, secrets and masking, exit codes, artifacts, OIDC cloud login (see the CI course)CI job execution flowWrite a CI job for opsctl
850–60opsctl v0.3: health, backup and deployFull code for the three subcommands, dispatch, exit codes, config options and troubleshooting treeopsctl execution path + interactive troubleshooting treeFinish v0.3 and self-test
—After classCheat sheet · Capstone lab“From API to deploy” end-to-end scriptFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / objectsLab
HTTP status codes and curl exit codes✓·✓✓··✓✓--fail-with-body,-w '%{http_code}', rc 22 / 28 / 7M1
Retries, backoff and timeouts✓·✓✓···✓--retry,--max-time,util::retryM1 / M8
JSON processing and cloud CLIs✓✓····✓·--query,-o tsv,jq -rM2
Parallelism and bulk SSH··✓·····xargs -0 -P,parallel --joblog,ssh -n -o BatchMode=yesM3
Atomic switchover and rollback···✓✓··✓ln -sfn,mv -T,readlinkM4
Backup, verification and rotation····✓✓·✓tar,sha256sum -c,find -print0 | sort -zM5
Concurrency protection···✓✓✓·✓flock -n,mktemp,trapM5 / M6
Scheduled runs·····✓··crontab -e,OnCalendar=,systemctl --user list-timersM6
Running scripts in CI·✓····✓✓shell: bash,::add-mask::,.gitlab-ci.ymlM7

Out of scope for this lesson (and where to learn it)

TopicWhy it is not in this lessonWhere to learn it
Creating cloud resources, networking and permission design (VMs, VNets, IAM, RBAC)This lesson only scripts cloud CLIs as “commands that return JSON”, and only does read-only queriesLinux course, Lesson 3 (Azure) · Linux course, Lesson 4 (AWS)
The CI/CD platforms themselves (runners, pipeline syntax, environment approvals, OIDC setup details)This lesson only covers “how to make scripts run reliably in CI”GitHub, 8 hours · GitLab, 8 hours
Desired state across many hosts, idempotent configuration, rolling release orchestrationBeyond a dozen or so hosts, or when idempotency is needed, shell loops are no match for configuration management toolsAnsible, 8 hours
Containerized deployment (images, Kubernetes rolling updates)The deploy target in this lesson is “a single directory”, used to explain the atomic switchover principleDocker / Kubernetes courses (later in the learning path)
bats testing, ShellCheck / shfmt, releasing opsctl v1.0Belongs to the next lesson’s topicsLesson 7
Full systemd unit syntax, journaldThis lesson only uses the parts needed for timersLinux course, Lesson 2

How to use this course

10 pages per module
Theory · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · voice · video. The animations in Module 1 and Module 4 together form the core of this lesson: first see “what actually happens in one API call with retries”, then “how a deploy script switches atomically and rolls back”.
Zero-cost default path
All labs can be completed locally: the mock API uses the Python standard library, and the deploy target is a local directory + python3 -m http.server, and the SSH target can be localhost. All cloud CLI sections are labeled “optional, read-only”.
Progress and voice
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress (stored in this browser). The “Voice” page uses the browser’s built-in Web Speech API (en-US) to read the narration aloud.
Version notes Baseline Bash 5.3 (Ubuntu 26.04 ships this; 24.04 has 5.2.21, and all examples here also work on 5.2). Upstream latest versions as verified on 2026-11-17: curl 8.23.0 (2026-10-14), Azure CLI 2.93.0 (2026-11-15), AWS CLI 2.40.4 (2026-11-16), jq 1.8.2, GNU parallel 20261022, mikefarah yq 4.54.3, ShellCheck 0.11.0; GitHub official actions/checkout current major version v7. Distro repository versions are usually older (for example, Ubuntu 24.04’s curl is 8.5.0), so this lesson marks options that “need curl ≥ x.y”. macOS ships with Bash 3.2 and BSD tools: mv -T,sha256sum,flock,sort -z etc. require Homebrew’s coreutils / util-linux, or use the alternatives given in this lesson. Ubuntu 26.04 Defaults to the Rust-based coreutils (uutils). The options used in this lesson are all common ones, but please run it once in CI for real (see Module 7).
Prerequisites This lesson assumes you have completedLesson 4(strict mode, trap, locks, logging, retries → opsctl v0.2) andLesson 5(text and data processing,find -print0 | xargs -0, jq). opsctl picks up from the Lesson 4 git tag v0.2.0 and continues from there (Module 0, step 3, describes the interfaces v0.2 provides, such as util::retry,util::lock,util::cleanup_add,config::get etc.; without that tag, first complete the Lesson 3 and 4 capstone labs).

Module 0 · Preparation: cloud account (optional) and API sandbox

Start a local mock API that “fails on purpose”, confirm opsctl is at v0.2.0; you only need the cloud CLIs if you already have an account
Before class ≈ 10 minBash 5.x · Python 3 standard libraryOptional: read-only az / aws permissions
Prerequisites
  • A Bash 5.x environment: the Linux course’s linuxlab VM, WSL2, macOS (Homebrew bash + coreutils) or container docker run --rm -it -v "$PWD":/work -w /work bash:5.3 (the official image is based on Alpine, so you need apk add --no-cache curl jq python3 coreutils util-linux tar).
  • Working directory ~/bashlab, sample data is generated by the Lesson 1 ~/bashlab/make-data.sh script (this lesson uses data/servers.csv,data/inventory.json).
  • Tools: curl,jq,python3,flock (util-linux),tar,sha256sum; Module 3 optionally needs GNU parallel and ssh; Module 6 needs systemd (WSL2 needs /etc/wsl.conf enabled systemd=true).
  • Optional (Module 2 cloud part): logged-in Azure CLI (Reader role is sufficient) and/or AWS CLI v2 (able to call sts get-caller-identity and ec2 describe-* with read-only permissions). This lesson creates no cloud resources, so the cost is zero.

Step 1: check tools

cd ~/bashlab 2>/dev/null || mkdir -p ~/bashlab && cd ~/bashlab
bash --version | head -1
for c in curl jq python3 flock tar sha256sum parallel ssh az aws; do
  if command -v "$c" >/dev/null; then printf '%-10s ok  %s\n' "$c" "$(command -v "$c")"
  else printf '%-10s --  not installed\n' "$c"; fi
done
curl --version | head -1
GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
curl       ok  /usr/bin/curl
jq         ok  /usr/bin/jq
python3    ok  /usr/bin/python3
flock      ok  /usr/bin/flock
tar        ok  /usr/bin/tar
sha256sum  ok  /usr/bin/sha256sum
parallel   --  not installed
ssh        ok  /usr/bin/ssh
az         --  not installed
aws        --  not installed
curl 8.5.0 (x86_64-pc-linux-gnu) libcurl/8.5.0 OpenSSL/3.0.13 zlib/1.3 ...
# Debian / Ubuntu
sudo apt-get install -y curl jq python3 util-linux parallel openssh-client
# macOS (Homebrew): newer bash, GNU coreutils (provides gsha256sum/gmv etc.), flock
brew install bash curl jq coreutils flock parallel
The curl version matters Options used in this lesson and their minimum versions: --retry-connrefused (7.52.0),--parallel (7.66.0),--retry-all-errors (7.71.0),--fail-with-body (7.76.0),--json (7.82.0),-w '%{header_json}' (7.83.0),-w '%header{name}' (7.84.0),-w '%{num_retries}' (8.9.0). Ubuntu 24.04's curl 8.5.0 does not support the last one (running it reports unknown --write-out variable: 'num_retries').

Step 2: start a local mock API (a zero-cost “server that fails on purpose”)

Public test APIs (for example GitHub's unauthenticated endpoints) are rate-limited and flaky, so they are not suitable for practicing retries over and over. This small service, which uses only the Python standard library, can produce on demand 503s, timeouts and pagination:

mkdir -p ~/bashlab/mock && cat > ~/bashlab/mock/mockapi.py <<'PY'
#!/usr/bin/env python3
"""Local mock API for the opsctl course (standard library only).
Usage: python3 mockapi.py [port]   default 8000, listens only on 127.0.0.1
  GET /healthz                  -> 200 {"status":"ok"}
  GET /items?page=N&per_page=M  -> 23 records, paginated, with Link header (next/prev/last)
  GET /flaky?fail=K&key=X       -> the first K responses for the same key return 503 + Retry-After: 1, then 200
  GET /slow?sec=S               -> sleeps S seconds, then returns 200
  GET /status/CODE              -> returns the given status code with a JSON error body
"""
import json, sys, time, threading
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

TOTAL = 23
HITS = {}
LOCK = threading.Lock()

class H(BaseHTTPRequestHandler):
    def send_json(self, code, obj, headers=None):
        body = (json.dumps(obj) + "\n").encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        for k, v in (headers or {}).items():
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        u = urlparse(self.path)
        q = {k: v[0] for k, v in parse_qs(u.query).items()}
        if u.path == "/healthz":
            return self.send_json(200, {"status": "ok"})
        if u.path == "/items":
            page, per = int(q.get("page", 1)), int(q.get("per_page", 10))
            last = max(1, -(-TOTAL // per))
            start = (page - 1) * per
            items = [{"id": i, "name": f"srv-{i:02d}"} for i in range(start + 1, min(start + per, TOTAL) + 1)]
            base = f"http://{self.headers.get('Host')}/items?per_page={per}&page="
            links = []
            if page < last:
                links.append(f'<{base}{page + 1}>; rel="next"')
            if page > 1:
                links.append(f'<{base}{page - 1}>; rel="prev"')
            links.append(f'<{base}{last}>; rel="last"')
            return self.send_json(200, items, {"Link": ", ".join(links), "X-Total-Count": str(TOTAL)})
        if u.path == "/flaky":
            fail, key = int(q.get("fail", 2)), q.get("key", "default")
            with LOCK:
                HITS[key] = HITS.get(key, 0) + 1
                n = HITS[key]
            if n <= fail:
                return self.send_json(503, {"error": "temporarily unavailable", "attempt": n}, {"Retry-After": "1"})
            return self.send_json(200, {"status": "ok", "attempt": n})
        if u.path == "/slow":
            time.sleep(float(q.get("sec", 3)))
            return self.send_json(200, {"status": "ok", "slept": q.get("sec", 3)})
        if u.path.startswith("/status/"):
            code = int(u.path.rsplit("/", 1)[1])
            return self.send_json(code, {"error": f"forced {code}"})
        return self.send_json(404, {"error": "not found", "path": u.path})

    def log_message(self, fmt, *args):
        sys.stderr.write("mockapi %s\n" % (fmt % args))

if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
    print(f"mockapi listening on http://127.0.0.1:{port}", flush=True)
    ThreadingHTTPServer(("127.0.0.1", port), H).serve_forever()
PY
# start in background, log to file; note the PID for stopping later
python3 ~/bashlab/mock/mockapi.py 8000 2>~/bashlab/mock/mock.log &
echo $! > ~/bashlab/mock/mock.pid
sleep 1; curl -sS http://127.0.0.1:8000/healthz
mockapi listening on http://127.0.0.1:8000
{"status": "ok"}

Stop: kill "$(cat ~/bashlab/mock/mock.pid)". The service only listens on 127.0.0.1 and is not exposed to the network. The /flaky counter is tracked per key key, so use a new key for each exercise (or restart the service) to reset.

Step 3: start from opsctl v0.2.0 from Lesson 4

This lesson builds on the code delivered by the Lesson 4 capstone lab opsctl v0.2.0 (git tag v0.2.0) and continues from it, with no new starter code. v0.2 already provides all the infrastructure this lesson needs

  • bin/opsctl: set -Eeuo pipefail + shopt -s inherit_errexit; OPSCTL_HOME (readlink -f parsing, supports ln -s install); readonly OPSCTL_VERSION="0.2.0"; opsctl::list_commands reads each lib/cmd_*.sh 's # opsctl-summary: comments to generate help; opsctl::load_command loads lib/cmd_<name>.sh by name and calls cmd::<name>; util::setup_traps (ERR reporting, EXIT cleanup, signals).
  • lib/log.sh: log::debug/info/warn/error, writes to stderr (format time level opsctl[PID]: message).
  • lib/util.sh: EX_OK/EX_ERR/EX_USAGE/EX_DEP (0/1/2/3),util::die <msg> [code],util::usage_error (exit code 2),util::require_cmd (exit code 3),util::cleanup_add,util::mktemp_dir <var>,util::lock <name> [wait],util::retry <tries> <delay> <cmd…> (exponential backoff + full jitter).
  • lib/config.sh: OPSCTL_DEFAULTS allowlist,config::set_flag / config::get; precedence flag > environment variable OPSCTL_<KEY> > etc/opsctl.conf (key = value, parsed only, never sourced) > defaults.
cd ~/bashlab/opsctl
git describe --tags; git status --short      # expect v0.2.0, and a clean working tree
grep -n '^readonly OPSCTL_VERSION=' bin/opsctl
export NO_COLOR=1
bin/opsctl -V
bin/opsctl help health; echo "rc=$?"         # v0.2 does not have health yet
v0.2.0
30:readonly OPSCTL_VERSION="0.2.0"
opsctl 0.2.0
2026-11-17T03:01:26-0500 ERROR opsctl[22748]: unknown command: health
Try 'opsctl --help' for more information.
rc=2
No v0.2.0? In order, complete theLesson 3 capstone lab(v0.1.0; the “if you skipped earlier modules” section gives an 8-step copy procedure) and theLesson 4 capstone lab(v0.2.0). This lesson does not repeat the starter code, to avoid diverging from the real Lesson 3 and 4 implementations.

Step 4 (optional): read-only cloud CLI login

# Azure: browser / device-code login, confirm the current subscription (read-only is enough)
az login --use-device-code
az account show --query '{name:name, id:id, user:user.name}' -o table

# AWS: recommended IAM Identity Center (SSO); confirm identity
aws configure sso          # or reuse the configuration from Linux course Lesson 4
aws sts get-caller-identity --query Account --output text
Security Never write long-term access keys into scripts or repositories. All cloud commands in this lesson are show / list / describe read-only calls, incurring no resource charges (API calls are free, though your organization may bill for audit logs, which you can ignore). When logging in to the cloud from CI, use OIDC (see Module 7).

Step 5 (optional): prepare an SSH target for Module 3

# Use localhost as a “remote host”, to practice the SSH loop at zero cost
sudo apt-get install -y openssh-server && sudo systemctl enable --now ssh
[[ -f ~/.ssh/id_ed25519 ]] || ssh-keygen -t ed25519 -N '' -f ~/.ssh/id_ed25519
cat ~/.ssh/id_ed25519.pub >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys
ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new localhost 'hostname; uptime'

Warm-up: answer from memory (30 seconds)

curl https://example.com/missing When a 404 is returned, what is the exit code of $? ?

0. For curl, “receiving a complete HTTP response” counts as a successful transfer, and a 404 is just response content. Only when adding -f / --fail-with-body , HTTP ≥ 400 turns into exit code 22. This is the first key point of Module 1.

In Lesson 4’s set -e setting, does a failing command inside if cmd; then cause an exit?

No. In if/while conditions,&&/|| non-final commands,! or after the negation operator !, errexit is ignored (Bash manual, The Set Builtin). The health checks and retry loops in this lesson rely heavily on this: if ! cmd::health …; then rollback; fi.

Environment self-check checklist

Module 1 · Calling HTTP APIs: curl, status codes, retries and pagination

00:00 – 06:00 · “curl returns 0” does not mean “the request succeeded” — separate the transport layer from the HTTP layer first, then talk about retries
6 mincurl 8.23.0 · minimum version markers 7.76 / 8.9★★★★★
Learning objectives
  • Explain the relationship between curl exit codes and HTTP status codes, and use --fail-with-body and -w '%{http_code}' to write calls that correctly judge success or failure.
  • Set --connect-timeout and --max-time, understand that --retry only retries “transient errors” (timeouts, 408 / 429 / 500 / 502 / 503 / 504 etc.), uses exponential backoff by default (starting at 1 second, doubling, capped at 10 minutes) and honors Retry-After.
  • Paginate by Link: <…>; rel="next" header, merge multi-page results into JSON Lines and pass them to jq.
  • Know when not to retry (non-idempotent POST), and how to reduce the risk with an idempotency key (Idempotency-Key).
Prerequisites: Lesson 4’s exit codes and set -e exceptions, plus jq from Lesson 5. Importance:★★★★★ (nearly all ops automation calls APIs)

What: the role curl plays in a script

curl is a “transfer tool”: it handles DNS resolution, the TCP / TLS handshake, sends the request and receives the response, then writes the response body to stdout (or to the file given by -o ), writes progress and errors to stderr, and exits with a exit code. The key point is that curl's exit code describes whether the transfer succeeded, not whether the business operation succeeded. A server returning HTTP/1.1 500, for curl, is still “a complete response received”, and the default exit code is 0.

Why: why API calls in scripts keep going wrong

  • Silent failures: no -f, so 404 / 500 HTML error pages are passed to jq as normal JSON, and jq then reports parse error errors, hiding the real cause.
  • Hangs forever: curl has no total timeout by default, so if the peer accepts the connection but never responds, cron / CI jobs can hang for hours.
  • Transient failures: load balancer switchovers, rate limiting (429) and 503s during rolling releases are all errors that “just retry later” fixes; not retrying causes false alarms, while blind retries amplify the failure (retry storms).
  • Only the first page is fetched: most REST APIs paginate by default (GitHub defaults to 30 items per page), so scripts that don't follow pages silently miss data as resources grow.

How: decision flow for a single call

  1. Transport phase: DNS (failure → exit code 6), TCP connect (refused / unreachable → 7), TLS (certificate problems → 60 / 35), capped by --connect-timeout ; the whole transfer is capped by --max-time (timeout → 28).
  2. HTTP phase: the status line and headers are received. With -f (--fail) is set, a status code ≥ 400 → exit code 22 and does not output the response body; --fail-with-body (curl 7.76.0+) also returns 22, but keeps the response body, which is handy for logging the error message the API returns. The two are mutually exclusive.
  3. Retry decision (only when --retry N is given, retries happen): timeouts, FTP 4xx, HTTP 408, 429, 500, 502, 503, 504, 522 and 524 are treated as transient errors; the wait time starts at 1 second by default and doubles each time, capped at 10 minutes; if the response includes Retry-After (since 7.66.0), curl waits for that long. --retry-delay switches to a fixed interval; --retry-max-time caps the total duration of the whole retry process; --retry-connrefused also treats “connection refused” as a transient error; --retry-all-errors (7.71.0) retries every error; the official docs call it a “sledgehammer” and do not recommend using it by default.
  4. Output: -w/--write-out prints variables after the transfer ends, for example %{http_code},%{time_total},%{url_effective},%{header_json} (7.83.0),%header{link} (7.84.0),%{num_retries} (8.9.0),%{exitcode} and %{errormsg} (7.75.0).
curl exit codeMeaningWorth retrying?
0Transfer succeeded (does not mean HTTP 2xx!)—
6Hostname cannot be resolvedUsually no (configuration error); a few retries are fine if DNS is flaky
7Cannot connect (refused / unreachable)Yes, within a service restart window (--retry-connrefused)
22HTTP ≥ 400 (only when -f / --fail-with-body is used)Check the status code: 5xx / 429 are fine to retry; 4xx (except 408 / 429) should not be retried
28Timeout (connect or total time)Yes, but always with an overall time limit
35 / 60TLS handshake failure / certificate verification failureNo; do not use -k to hide
52 / 56Empty response / failure to receive data (connection reset)Yes (common when a backend restarts)

When: curl, wget, HTTPie or Python?

ToolSuited forNot suited for
curlAPI calls and health checks in scripts; ships with almost every image; exit codes and -w make success or failure easy to judgeComplex auth flows (OAuth refresh), heavy JSON construction
wgetDownloading files, recursive mirroring, resumable transfersREST APIs (less convenient than curl for methods, headers and status handling)
HTTPie (http)Interactive debugging with nice outputScripts (needs extra installation; different exit-code conventions)
Python requests / GoMulti-step auth, complex pagination / retry strategies, clients that need unit testsGlue tasks that take “three lines”
Cloud SDKs / CLIs (az, aws)Cloud vendor APIs: automatic signing, pagination and retries built in— (see Module 2)
Common misconceptions① “curl -s “Silent means safe”—-s also hides the error message, so always write -sS (silent progress, but errors still shown). ② “adding --retry 5 means you can survive a 500”— without --max-time , a single request can hang forever and retries never get a chance; without --retry-max-time , exponential backoff can add up to tens of minutes. ③ “-f makes 4xx also get retried”—--retry it only checks whether the status code is on the transient list, so a 404 is never retried (unless --retry-all-errors). ④ “POST can also be retried freely”— non-idempotent requests may create two orders or two VMs on retry, so the API must support idempotency keys or deduplicate at the business level.

Architecture diagram: curl decision chain and exit codes

DNS resolutionFailure → rc 6 TCP / TLS handshakerc 7 / 35 / 60 · --connect-timeout Send requestMethod · headers · --json body Receive status lineHTTP/1.1 503Retry-After: 1 Write out + -w%{http_code} etc. What determines the exit code • Transfer failure: 6 / 7 / 28 / 35 / 52 / 56 … (unrelated to status code) • Got 2xx/3xx: 0 • Got ≥400: 0 by default; 22 with -f (discards body); 22 with --fail-with-body (keeps body) • --retry N: transient errors (timeouts, some 408/429/5xx) → sleep (starts at 1s, doubling / Retry-After) → retry • --max-time restarts the timer on each attempt; --retry-max-time limits the whole process Three output channels stdout: response body (or -o file) stderr: error messages (still shown with -sS) $?: exit code (what scripts check) -w: status code, timing, headers (appended to stdout)
Figure 1-1 curl completes the transfer first, then maps the HTTP status code to an exit code based on the options; retries are a loop wrapped around this chain

Data flow diagram: timeline of retries and exponential backoff

Time #1 503 sleep 1s #2 503 sleep 2s #3 timeout sleep 4s (uses Retry-After when present) #4 200 --retry-max-time: counts from the first attempt; once reached, no new retries start Each attempt is limited by --max-time (the timer resets on retry) When writing your own retry loop in a script, add jitter (random 0–1s) so a batch of clients does not wake up at the same time Built into curl: 1s → 2s → 4s → … capped at 10 minutes; --retry-delay N switches to a fixed N seconds
Figure 1-2 Exponential backoff spreads out the retry intervals, giving the peer time to recover; the total duration must be capped

Core animation (part 1): one API call with retries and backoff

Pick a scenario and step through the real interaction between the client (curl in the script) and the server: DNS / connection / request / status code / retry decision / sleep / final exit code. The terminal below shows the matching real commands and curl output (verified against this lesson’s mockapi).

Script / curlAttempt 0$? = ? DNS / TCP / TLS Request → response Retry decision API server— Timelinet = 0.0sRetries left —
Ready.
$ # mockapi running on 127.0.0.1:8000

Core options quick reference

OptionPurposeKey points / minimum version
-sSSilent progress bar, but still prints errorsDefault choice in scripts
-f / --fail-with-bodyExit code 22 when HTTP ≥ 400The latter keeps the response body (7.76.0); the two are mutually exclusive
-o FILE / -D FILEWrite response body / headers to a file-D - Write to stdout
-w FORMATPrint variables after the transfer%{http_code} %{time_total} %header{link} (7.84.0)
--connect-timeout SLimits only the connection phase (DNS + TCP + TLS)Decimals allowed
-m / --max-time SOverall time cap for a single transferTimeout exit code 28; timer restarts on retry
--retry NRetry transient errors N timesDoubles from 1s, capped at 10 minutes; honors Retry-After
--retry-max-time SOverall cap on retry durationNo new retries start once reached
--retry-delay SFixed retry interval (turns off exponential backoff)0 restores the default
--retry-connrefusedAlso retries when the connection is refused7.52.0; useful during service restart windows
--retry-all-errorsRetry on any error7.71.0; use with -f Retries 4xx — use with caution
--json DATAPOST JSON, sets Content-Type / Accept automatically7.82.0; @file / @-
-H 'Authorization: Bearer …'Auth headerUse -H @file or --config to keep the token from appearing in ps .

1. Exit code vs status code (actual run)

B=http://127.0.0.1:8000
curl -sS -o /dev/null -w '%{http_code}\n' "$B/status/503"; echo "rc=$?"
curl -fsS "$B/status/404"; echo "rc=$?"
curl -sS --fail-with-body "$B/status/404"; echo "rc=$?"
503
rc=0
curl: (22) The requested URL returned error: 404
rc=22
curl: (22) The requested URL returned error: 404
{"error": "forced 404"}
rc=22

How to verify: The first line shows 503, yet rc=0— this is why scripts that only look at “ $?” treat the failure as success. Common mistakes: Writing both -f --fail-with-body together (mutually exclusive, causes an error). Production use: When a call fails, write the --fail-with-body error JSON you get back to the log, which makes troubleshooting much faster.

2. Get both the body and the status code

# Option A: body to file, status via -w (safest, recommended)
body=$(mktemp)
code=$(curl -sS -o "$body" -w '%{http_code}' --connect-timeout 3 --max-time 10 "$B/status/422") || code=000
echo "code=$code"; jq -r '.error' "$body"; rm -f "$body"

# Option B: append the status code on the last line, then split it with parameter expansion
resp=$(curl -sS -w '\n%{http_code}' "$B/status/422")
code=${resp##*$'\n'}; body=${resp%$'\n'*}
echo "code=$code body=$body"
code=422
forced 422
code=422 body={"error": "forced 422"}

Option B also works when the response body itself does not end with a newline; but large responses stay whole in a variable, and binary content gets truncated by Bash (NUL bytes), so for downloads always use Option A. || code=000 Handling transfer failures (here curl still prints 000).

3. One observable call

curl -sS -o /dev/null \
  -w 'code=%{http_code} total=%{time_total}s connect=%{time_connect}s url=%{url_effective}\n' \
  "$B/healthz"
code=200 total=0.000661s connect=0.000094s url=http://127.0.0.1:8000/healthz

4. Timeouts and retries (actual run)

curl -sS --max-time 1 "$B/slow?sec=3"; echo "rc=$?"
curl -fsS --retry 3 "$B/flaky?fail=2&key=demo1"; echo "rc=$?"
curl -S --retry 3 -o /dev/null "$B/flaky?fail=2&key=demo2"     # without -s, you can see the retry notices
curl -sS --retry 2 --retry-connrefused --retry-delay 1 http://127.0.0.1:9; echo "rc=$?"
curl: (28) Operation timed out after 1001 milliseconds with 0 bytes received
rc=28
{"status": "ok", "attempt": 3}
rc=0
Warning: Problem : HTTP error. Will retry in 1 seconds. 3 retries left.
…(each retry afterwards prints one line, eventually succeeds)
curl: (7) Failed to connect to 127.0.0.1 port 9 after 1 ms: Couldn't connect to server
curl: (7) Failed to connect to 127.0.0.1 port 9 after 0 ms: Couldn't connect to server
curl: (7) Failed to connect to 127.0.0.1 port 9 after 0 ms: Couldn't connect to server
rc=7

Note: When retrying, without and without -f , -o the response body of every failed attempt goes to stdout, so you get three JSON documents concatenated (verified). Adding -f discards the failed response bodies and keeps only the last successful result; when using -o file , curl truncates the file before each retry.

# Recommended production combo (GET / idempotent requests)
curl -fsS --connect-timeout 3 --max-time 10 \
     --retry 4 --retry-max-time 60 --retry-connrefused \
     -H 'Accept: application/json' "$url"

5. Paginate by Link header

curl -sS -o /dev/null -w '%header{link}\n' "$B/items?per_page=10&page=1"    # curl ≥ 7.84
<http://127.0.0.1:8000/items?per_page=10&page=2>; rel="next", <http://127.0.0.1:8000/items?per_page=10&page=3>; rel="last"
# Compatible with older curl: use -D to write headers to a temp file, then extract rel="next" with sed
api::get_all() {   # usage: api::get_all URL   → outputs all page elements as JSON Lines
  local url=$1 hdr body
  hdr=$(mktemp)
  while [[ -n $url ]]; do
    body=$(curl -fsS --retry 3 --connect-timeout 3 --max-time 10 -D "$hdr" "$url") \
      || { rm -f "$hdr"; return 1; }
    jq -c '.[]' <<<"$body"
    url=$(tr -d '\r' <"$hdr" | sed -n 's/^[Ll]ink:.*<\([^>]*\)>; *rel="next".*/\1/p')
  done
  rm -f "$hdr"
}
api::get_all "$B/items?per_page=10" | sed -n '1,3p'
api::get_all "$B/items?per_page=10" | wc -l
{"id":1,"name":"srv-01"}
{"id":2,"name":"srv-02"}
{"id":3,"name":"srv-03"}
23

Key points: HTTP headers end with \r\n , so you must first strip it with tr -d '\r', otherwise the URL ends with \r, and the next request returns 400. Header names are case-insensitive (lowercase under HTTP/2 link:), so use [Ll]ink. Do not use | head -3 to truncate — under set -o pipefail , the upstream killed by SIGPIPE makes the whole pipeline fail (verified: Python reports BrokenPipeError), the 141 problem from Lesson 4.

6. POST JSON and idempotency key (example, not run against a real service)

idem=$(cat /proc/sys/kernel/random/uuid)     # one key per “business operation”, reuse on retry
jq -n --arg name "web-03" --arg env prod '{name:$name, env:$env}' |
  curl -sS --fail-with-body --max-time 15 \
       -H "Idempotency-Key: $idem" \
       -H @"$HOME/.config/opsctl/auth.header" \
       --json @- https://api.example.com/v1/servers

Use jq -n --arg to build the JSON, avoiding quoting and injection problems from hand-concatenated strings. -H @file (curl 7.55.0+) reads headers from a file, so the token never appears in ps output or shell history. Whether Idempotency-Key is supported depends on the API (Stripe and others support it); if it is not supported,Do not use on POST --retry.

Lab: make robust calls to the mock API

Goal and environment: mockapi runs on 127.0.0.1:8000 (Module 0, Step 2). All local, zero cost.
B=http://127.0.0.1:8000; curl -sS "$B/healthz"
Observe a “false success”:
curl -sS "$B/status/500" >/dev/null; echo "no -f: rc=$?"
curl -fsS "$B/status/500" >/dev/null; echo "with -f: rc=$?"
no -f: rc=0
curl: (22) The requested URL returned error: 500
with -f: rc=22
Write a retry function (saved as ~/bashlab/m1-api.sh):
cat > ~/bashlab/m1-api.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
B=${B:-http://127.0.0.1:8000}

# api::call METHOD PATH → prints response body to stdout; returns 1 when the status code is not 2xx, and writes the error body to stderr
api::call() {
  local method=$1 path=$2 body code
  body=$(mktemp)
  code=$(curl -sS -X "$method" -o "$body" -w '%{http_code}' \
           --connect-timeout 3 --max-time 10 \
           --retry 4 --retry-max-time 30 --retry-connrefused \
           "$B$path") || code=000
  if [[ $code == 2?? ]]; then
    cat "$body"; rm -f "$body"; return 0
  fi
  printf 'api::call %s %s → HTTP %s: %s\n' "$method" "$path" "$code" "$(head -c 300 "$body")" >&2
  rm -f "$body"; return 1
}

api::call GET /healthz
api::call GET "/flaky?fail=2&key=lab-$$"
api::call GET /status/404 || echo "→ 404 correctly identified as failure (rc=$?)"
EOF
bash ~/bashlab/m1-api.sh
{"status": "ok"}
{"status": "ok", "attempt": 3}
api::call GET /status/404 → HTTP 404: {"error": "forced 404"}
→ 404 correctly identified as failure (rc=1)

Why did /flaky succeed? Because --retry automatically handled the first two 503s and honored Retry-After: 1. [[ $code == 2?? ]] Use a wildcard to match all 2xx.

Timeout: add /slow?sec=15 to the script and observe about 10 seconds later HTTP 000; then change --max-time to 20 and observe success. Think about: --retry 4 what is the longest wait time? (Hint: each attempt takes up to 10 seconds plus backoff, but --retry-max-time 30 the overall limit (about 30 seconds) stops new attempts from starting.)
Pagination: add the api::get_all from the “Commands” page to the script, count the items and take the last 3 by name:
api::get_all "$B/items?per_page=7" | jq -r '.name' | sort | tail -n 3
srv-21
srv-22
srv-23
(Optional) real public API: the GitHub API rate-limits unauthenticated requests to 60 per hour, so it is good for observing real Link and rate-limit headers (read-only, free):
curl -sS -o /dev/null -D - 'https://api.github.com/orgs/bminor/repos?per_page=2' \
  | grep -iE '^(link|x-ratelimit-remaining):'
x-ratelimit-remaining: 57
link: <https://api.github.com/organizations/…/repos?per_page=2&page=2>; rel="next", <…&page=…>; rel="last"
Verification and cleanup: tail ~/bashlab/mock/mock.log You can see each retry request; this module has no resources to clean up (mockapi is still needed later, so do not stop it yet).

Case 1: health check is all green, but the service is returning 500

Problem: The monitoring script curl -s http://svc/healthz && echo OK has never raised an alarm over the years. After a release, the app returned 500 with an error page; curl's exit code stayed 0, and users only discovered the outage 40 minutes later. Fix: Change it to curl -fsS --max-time 5 -o /dev/null -w '%{http_code}', explicitly compare against the expected status code, and write the first 300 bytes of the response body to the log. Limitations: A 200 status can still mean a “degraded” state, so the health endpoint should ideally return structured JSON (such as {"status":"ok","db":"ok"}) and validate key fields with jq.

Case 2: retry storm amplified the outage

Problem: Cron on 200 hosts all call the config center at second 0 of every minute; after the config center briefly returns 503, every script retries 10 times at a fixed 1-second interval, multiplying request volume 10x in an instant and taking the config center down completely. Fix:① exponential backoff (curl default) + random jitter (sleep "$((RANDOM % 30))" or systemd’s RandomizedDelaySec); ② honor Retry-After; ③ --retry-max-time cap the total duration; ④ the server returns 429 so clients back off. Limitations: Jitter adds per-attempt latency; for latency-sensitive tasks, this is a trade-off.

Case 3: pagination missed data, causing an accidental deletion

Problem: The “clean up untagged snapshots” script only read the first page of the API (100 items) and treated “snapshots not in the list” as orphans and deleted them. Fix: Fully paginate by Link: rel="next" or the API’s nextToken pagination; verify counts before deleting (compare with X-Total-Count or a second query); print a dry-run list first and confirm it manually. Configuration: This module’s api::get_all. Limitations: Data may change during pagination (new / deleted items), so critical operations should re-confirm based on snapshot IDs.

Common errors and fixes

parse error: Invalid numeric literal at line 1, column 10 (jq received HTML)

Cause: The API returned an HTML error page with a 4xx/5xx status (or a proxy’s login page), and curl did not -f, so it was handed to jq as normal output.

curl -sS -D - -o /tmp/body "$url" | head -5; head -c 300 /tmp/body

Fix: Add --fail-with-body, or first check %{http_code} and %{content_type} before handing it to jq.

curl: (28) Operation timed out after 10000 milliseconds with 0 bytes received

Cause: The connection succeeded, but the server did not respond within --max-time (slow query, deadlock, or packet loss at a network middlebox). If the message is “Connection timed out after … milliseconds”, it is stuck in the connect phase (firewall / security group dropping packets).

curl -sS -o /dev/null -w 'dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n' "$url"

Fix: Locate it using the per-phase times: connect large → network / security group; ttfb large → the server is slow to process. Set sensible values for --connect-timeout (3–5 seconds) and --max-time, and investigate on the server side.

curl: (60) SSL certificate problem: unable to get local issuer certificate

Cause: The container or minimal image lacks a CA certificate bundle, or the corporate proxy performs TLS interception.

ls /etc/ssl/certs/ca-certificates.crt; curl -v "$url" 2>&1 | grep -E 'issuer|CAfile'

Fix: Install ca-certificates; for a corporate CA, use --cacert corp-ca.pem or add it to the system trust store. Do not use -k/--insecure in scripts.

curl: unknown --write-out variable: 'num_retries'

Cause:%{num_retries} Needs curl 8.9.0+; Ubuntu 24.04's 8.5.0 does not support it (verified). Likewise %header{…} needs 7.84.0+.

curl --version | head -1

Fix: Check the version at the start of the script, or switch to a compatible approach (-D header file + sed); use a pinned-version image in CI.

Pagination loop never ends / page 2 returns 400 Bad Request

Cause: The URL extracted from the header file ends with \r; or the sed regex treats rel="last" as next, so it keeps requesting the last page.

printf '%q\n' "$url"      # if $'\r' appears at the end, this is the problem

Fix:tr -d '\r'; anchor the regex rel="next"; add a maximum-page guard to the loop (for example, 1000 pages).

Command-line tasks
1. Write a command that requests $url, with a 3-second connect timeout and a 10-second overall timeout, retries transient errors up to 3 times with total retry time capped at 30 seconds, and when HTTP ≥ 400 exits non-zero but keeps the error body.
curl -sS --fail-with-body --connect-timeout 3 --max-time 10 \
     --retry 3 --retry-max-time 30 "$url"
2. Output only $url the status code and total time (no response body), and, when the transfer fails, print 000.
curl -sS -o /dev/null -w '%{http_code} %{time_total}\n' --max-time 5 "$url" || true
# when the transfer fails, curl still prints 000 via -w; || true stops set -e from exiting
Scenario analysis
A colleague added --retry 5 --retry-all-errors to the POST call that creates a DNS record, and duplicate records appear occasionally. Analyze the cause and propose an improvement.

Cause: --retry-all-errors will retry after any error, including when “the request was processed by the server but the response timed out on the way back” (the client sees 28), so the same POST runs multiple times. POST is non-idempotent. Improvements: ① remove --retry-all-errors, so POST is never retried automatically; ② if the API supports idempotency keys, generate one Idempotency-Key and reuse it on retries; ③ switch to “check whether it exists first, then create” (or use an API with PUT / upsert semantics); ④ check the resource state before retrying.

Verified teaching videos

▶
mastering the curl command line - with Daniel Stenberg — Daniel Stenberg
English · long video (workshop recording, 2024 edition) · curl author speaking in person: URL, HTTP options, retries, -w, config files. The curl.se video page lists it as “Mastering the curl command line (2024)”
▶
using curl better - with curl creator Daniel Stenberg — freeCodeCamp Talks
English · talk · practical tips for calling HTTP APIs
▶
Rock-solid curl with Daniel Stenberg — Daniel Stenberg
English · how the curl project keeps things stable (background, optional)

Official docs

Video storyboard (about 90 seconds)

This course material cannot generate video / MP3 directly, but storyboards and narration scripts are provided for a video tool to produce it.

Shot 1 · 0–15s
Frame: in the terminal curl -s …/healthz; echo $? output a 500 error page and 0; the frame flashes red.
Narration: curl returns zero, which only means “the transfer succeeded”, not “the request succeeded”.
Shot 2 · 15–40s
Frame: decision chain: DNS → connect → request → status code, plus -f then 500 turns into exit code 22.
Narration: with fail-with-body, any status code of 400 or above becomes exit code 22, while the error message is kept.
Shot 3 · 40–70s
Frame: on the timeline, 503, sleep 1 second, 503, sleep 2 seconds, 200; above it, a dashed line labeled retry-max-time.
Narration: retries only target transient errors, intervals grow exponentially, and Retry-After is honored. The total time must always have a cap.
Shot 4 · 70–90s
Frame: rel="next" in the Link header is highlighted; the loop pages through one page at a time, and the counter jumps from 10 to 23.
Narration: without paging, data is missed. Keep requesting the next link from the Link header until there is no next page.
or score ≥ 70% on the quiz

Module 2 · Scripting cloud CLIs: --query, --output and jq for az and aws

06:00 – 13:00 · Treat cloud CLIs as “commands that return JSON”: where to filter, what format to hand to Bash, and how to detect failure
7 minAzure CLI 2.93.0 · AWS CLI 2.40.4 · jq 1.8.2Cloud part optional · read-only★★★★☆
Learning objectives
  • Explain the difference between server-side filtering (--filters,--resource-group,--tag) and client-side filtering (--query JMESPath, jq) and their order.
  • Use -o tsv (az) / --output text (aws) + while IFS=$'\t' read -r to read results safely into Bash variables and arrays, and know when to switch to -o json | jq -r … | @tsv.
  • Avoid common scripting pitfalls: the AWS CLI v2 pager (AWS_PAGER="" / --no-cli-pager), automatic pagination and --output text interaction, the Windows az output’s \r, quoting differences, and region / subscription defaults.
  • Detect failure by exit code: AWS CLI's 252 / 253 / 254 / 255, and az's non-zero exit code + --only-show-errors.
Prerequisites: Lesson 5 jq, Module 1 of this lesson. Background on cloud operations is in Linux course Lesson 3 (Azure)andLesson 4 (AWS). Importance:★★★★☆

What: the cloud CLI output pipeline

az and aws are programs that “call the REST API → get JSON → optionally filter with JMESPath (--query) → format by --output format”. JMESPath is a JSON query language (Reservations[].Instances[].InstanceId,[?state=='running'],{name:name}), and both CLIs have the same syntax built in. Microsoft Learn explicitly states that az's query is applied client-side to the returned JSON before display formatting.

Why: why you cannot just grep table output

  • -o table is meant for humans: column widths get truncated, and column order and headings may change between versions.
  • Quoted JSON strings: id=$(az … --query id) you get "0000…" (including the quotes), and passing it to the next command gives “doesn't exist” — the typical example in the official troubleshooting docs.
  • AWS CLI v2 hands output to the pager by default (less), so in scripts and CI without a terminal it can hang or misbehave.

How: choose which layer to handle it at

  1. Server-side filtering (preferred; reduces data volume and API pagination): aws ec2 describe-instances --filters Name=instance-state-name,Values=running,az vm list -g rg-x,az resource list --tag env=prod.
  2. JMESPath --query: select fields, do simple filtering and renaming, and output tsv/text straight to Bash. No extra dependencies needed.
  3. jq: use it when you need complex logic (group_by,any(), variables --arg, string handling, merging several files) with -o json | jq.
DimensionAzure CLI (az)AWS CLI v2 (aws)
Machine-readable plain text-o tsv (multi-select fields need a list [a,b] to guarantee column order)--output text (lists go one per row, fields separated by Tab)
Default output format configaz config set core.output=json or environment variable AZURE_CORE_OUTPUTAWS_DEFAULT_OUTPUT or ~/.aws/config ’s output
pagination (API layer)Most list commands fetch everything automatically, fetch all pages by default; --no-paginate,--max-items,--page-size,--starting-token
terminal pagerNonev2 enables it by default; AWS_PAGER="" or --no-cli-pager to disable
Quiet mode--only-show-errors (hides warnings)— (warnings go to stderr)
Failure exit codesnon-zero (follow the official docs)252 syntax / 253 config or credentials / 254 service error / 255 other; 130 Ctrl-C
Debugging--debug (prints HTTP requests and responses)--debug
An AWS detail AWS docs note: when using --output text , the output will paginate first, and then --query runs on each page separately, which may produce unexpected extra output (for example, [0] returns only the first item of each page). For queries over the whole result set, use --output json.

When: Bash + CLI, or something else?

ScenarioRecommended
Read-only checks, reports, providing a single value to CI (subscription ID, image ID, IP)Bash + CLI + --query
Creating / modifying resources that must be repeatable and reviewableTerraform / Bicep / CloudFormation (IaC)
Heavy concurrent calls, complex retries, need for unit testsPython SDK (azure-*, boto3)
Configuring many hostsAnsible (azure.azcollection,amazon.aws)
Common misconceptions① “--query “--query can reduce API calls”— no, it runs on the client after all the data has been downloaded; to reduce the data volume, use server-side filtering. ② “-o tsv The column order of {a:…,b:…} is the order I wrote in the query”— object (dict) order is not guaranteed in tsv, so use a list [a, b]. ③ “JMESPath and jq have the same syntax”— the filter syntax is completely different (JMESPath literals use backticks `running` or single-quoted strings 'running'), so do not mix them. ④ “an az command copied from Windows also works in Bash”— quoting rules differ (PowerShell strips brackets and quotes; verified length(@) in PowerShell parses it incorrectly).

Architecture diagram: from API to Bash variables

Cloud REST APIARM / EC2 Query APIserver-side filtering takes effect here CLI automatic paginationsigning · retries · merged pages→ full JSON --queryJMESPath (client-side)select fields · filter · rename --outputjson · tsv/texttable · yaml · none Bash$(…) · read -rmapfile -t -o json | jq -rcomplex logic · @tsv · --argjq -e uses the exit code to express “found / not found” stderr: warnings, --debug logs, error messages $?: 0 success; aws 252/253/254/255; az non-zero AWS v2: in an interactive terminal, output also passes through the pager (less)
Figure 2-1 server-side filtering → automatic pagination → JMESPath → output format → Bash; complex processing is routed to jq

Data flow diagram: how tsv rows enter Bash variables

CLI output (tab-separated, one object per line) i-0…0001 ⇥ web-01 ⇥ 10.0.1.11i-0…0003 ⇥ api 01 ⇥ 10.0.2.21(spaces in names are not separators) while IFS=$'\t' read -rIFS contains only Tab → split by column-r: backslashes are not escaped< <(cmd): loop runs in the current shell variablesid=i-0…0003name="api 01"ip=10.0.2.21 Pitfall: when a field is empty, do consecutive tabs count as one separator? Tab is IFS whitespace, so consecutive tabs merge and empty columns “shift left”; if empty values are possible, have jq output a placeholder (// "-").
Figure 2-2 Reading tsv with Tab as IFS; empty values and Windows \r are the two big pitfalls

Interactive demo: same JSON, three ways to get the value

Data: a trimmed-down aws ec2 describe-instances output (3 instances, one with a space in its name and one stopped). After choosing a method, step through what each layer does to the data and what value Bash finally gets. The jq column output comes from local runs (jq 1.6 and 1.8 give the same result).

Ready.
$ export AWS_PAGER="" # turn off the pager first in scripts

Command quick reference

CommandPurposeKey parameters
az account show --query id -o tsvCurrent subscription ID-o tsv Strip quotes
az vm list -d --query "[?powerState=='VM running'].[name,resourceGroup]" -o tsvRunning VMs-d with power state and IP (makes extra API calls, so slower)
az resource list --tag env=prod --query "[].id" -o tsvFind resources by tagTag filtering happens server-side
aws sts get-caller-identity --query Account --output textCurrent accountthe cheapest “who am I” check
aws ec2 describe-instances --filters … --query … --output textInstance inventory--filters Server-side; --query Client-side
aws ec2 describe-regions --query 'Regions[].RegionName' --output textRegion listNote that text output puts each record on a single line with fields separated by tabs
AWS_PAGER="" aws … / --no-cli-pagerTurn off the v2 pagerRequired for scripts / CI
jq -r '…|@tsv',jq -e,jq --argComplex processing-e: exit code 1 when the result is null/false

1. JMESPath that works offline: az cloud list (no login needed)

az cloud list --query "[].{name:name, active:isActive, arm:endpoints.resourceManager}" -o tsv
az cloud list --query "[?isActive].name" -o tsv
az cloud show -n AzureCloud --query "endpoints.activeDirectory" -o tsv
az cloud show -n NoSuch; echo "rc=$?"
AzureCloud	True	https://management.azure.com/
AzureChinaCloud	False	https://management.chinacloudapi.cn
AzureUSGovernment	False	https://management.usgovcloudapi.net/
AzureGermanCloud	False	https://management.microsoftazure.de
AzureCloud
https://login.microsoftonline.com
ERROR: The cloud 'NoSuch' is not registered.
rc=1

Note that the first example uses an object {…}: here the column order happens to match the order written, but the official docs don't guarantee it, so use a list in scripts [name, isActive, endpoints.resourceManager]. The cloud list may differ between CLI versions.

2. Azure: read-only inspection (optional, requires login)

set -euo pipefail
export AZURE_CORE_OUTPUT=json          # Prevents a user's default output from being changed to table and breaking the script
sub=$(az account show --query id -o tsv)
echo "subscription=$sub"

# Running VMs: name, resource group, private IP (list → fixed column order)
while IFS=$'\t' read -r name rg ip; do
  printf '%-20s %-18s %s\n' "$name" "$rg" "$ip"
done < <(az vm list -d --only-show-errors \
          --query "[?powerState=='VM running'].[name, resourceGroup, privateIps]" -o tsv)

# Resource group count (JMESPath function)
az group list --query "length(@)" -o tsv
subscription=00000000-0000-0000-0000-000000000000
vm-linux-lab         rg-linux-lab       10.10.1.4
3

3. AWS: read-only inspection (optional, requires credentials)

set -euo pipefail
export AWS_PAGER=""                     # Turn off the v2 pager
export AWS_REGION=${AWS_REGION:-ca-central-1}
acct=$(aws sts get-caller-identity --query Account --output text)
echo "account=$acct region=$AWS_REGION"

aws ec2 describe-instances \
  --filters Name=instance-state-name,Values=running \
  --query 'Reservations[].Instances[].[InstanceId, Tags[?Key==`Name`]|[0].Value, PrivateIpAddress]' \
  --output text |
while IFS=$'\t' read -r id name ip; do
  printf '%s  %-12s %s\n' "$id" "$name" "$ip"
done
account=123456789012 region=ca-central-1
i-0a1b2c3d4e5f60001  web-01       10.0.1.11
i-0a1b2c3d4e5f60003  api 01       10.0.2.21

JMESPath backtick literals `Name` must go inside Bash single quotes or Bash will treat them as command substitution. Instances without a Name tag,|[0].Value return null, and text output shows None.

4. Same data processed with jq (actual run, offline JSON)

# ec2.json: trimmed describe-instances sample (3 instances; the name of api 01 contains a space, web-02 is stopped)
jq -r '.Reservations[].Instances[] | select(.State.Name=="running")
  | [.InstanceId, (.Tags[]? | select(.Key=="Name") | .Value), .PrivateIpAddress] | @tsv' ec2.json

# Count instances per state
jq -c '[.Reservations[].Instances[]] | group_by(.State.Name) | map({state: .[0].State.Name, n: length})' ec2.json

# Pass variables safely with --arg (don't concatenate Bash variables into the filter string)
jq -r --arg env prod '.Reservations[].Instances[]
  | select(any(.Tags[]?; .Key=="env" and .Value==$env)) | .InstanceId' ec2.json

mapfile -t ids < <(jq -r '.Reservations[].Instances[].InstanceId' ec2.json)
echo "${#ids[@]} ${ids[2]}"
i-0a1b2c3d4e5f60001	web-01	10.0.1.11
i-0a1b2c3d4e5f60003	api 01	10.0.2.21
[{"state":"running","n":2},{"state":"stopped","n":1}]
i-0a1b2c3d4e5f60001
i-0a1b2c3d4e5f60002
3 i-0a1b2c3d4e5f60003

5. Error-handling template

aws_ro() {   # Read-only aws call: report the failure reason in readable form
  local out rc=0
  out=$(aws --no-cli-pager "$@" 2>&1) || rc=$?
  case $rc in
    0)   printf '%s\n' "$out" ;;
    253) log::error "AWS credentials or configuration is invalid: $out"; return 3 ;;
    254) log::error "AWS service rejected the request (permissions / parameters): $out"; return 1 ;;
    252) log::error "Command syntax error: $out"; return 2 ;;
    *)   log::error "aws failed rc=$rc: $out"; return 1 ;;
  esac
}
aws_ro sts get-caller-identity --query Arn --output text

Note: 2>&1 Merging errors into out makes logging easier. On success, any warnings also get mixed into the output, so only use this pattern for commands that return a single value; otherwise write stderr to a temp file. The exit code meanings come from the AWS CLI User Guide, “Command line return codes”.

Lab: offline practice + optional read-only cloud queries

Prepare offline data (zero cost, no account needed):
mkdir -p ~/bashlab/m2 && cd ~/bashlab/m2
cat > ec2.json <<'EOF'
{"Reservations":[
 {"Instances":[{"InstanceId":"i-0a1b2c3d4e5f60001","InstanceType":"t3.micro","State":{"Name":"running"},"PrivateIpAddress":"10.0.1.11","Tags":[{"Key":"Name","Value":"web-01"},{"Key":"env","Value":"prod"}]},
               {"InstanceId":"i-0a1b2c3d4e5f60002","InstanceType":"t3.small","State":{"Name":"stopped"},"PrivateIpAddress":"10.0.1.12","Tags":[{"Key":"Name","Value":"web-02"},{"Key":"env","Value":"prod"}]}]},
 {"Instances":[{"InstanceId":"i-0a1b2c3d4e5f60003","InstanceType":"t3.micro","State":{"Name":"running"},"PrivateIpAddress":"10.0.2.21","Tags":[{"Key":"Name","Value":"api 01"},{"Key":"env","Value":"staging"}]}]}
]}
EOF
jq '.Reservations | length' ec2.json
2
Read into an array and process each instance one by one: read the running instances into three parallel arrays and print “name → IP”.
ids=(); names=(); ips=()
while IFS=$'\t' read -r id name ip; do
  ids+=("$id"); names+=("$name"); ips+=("$ip")
done < <(jq -r '.Reservations[].Instances[] | select(.State.Name=="running")
           | [.InstanceId, (.Tags[]? | select(.Key=="Name") | .Value // "-"), .PrivateIpAddress // "-"] | @tsv' ec2.json)
for i in "${!ids[@]}"; do printf '%s → %s\n' "${names[i]}" "${ips[i]}"; done
web-01 → 10.0.1.11
api 01 → 10.0.2.21
Generate TSV from dataset inventory.json: Lesson 1's ~/bashlab/data/inventory.json has the same content as servers.csv (fields name / env / region / ip / role).
jq -r '.[] | select(.env=="prod") | [.name, .region, .ip] | @tsv' ~/bashlab/data/inventory.json

Output depends on your dataset (example). Think about it: does the line with a quoted comma still need special handling in JSON? (No. That is exactly why “CSV has boundary problems, JSON doesn't.”)

(Optional, Azure, read-only):
az account show --query "{sub:name, tenant:tenantId}" -o jsonc
az group list --query "[].[name, location]" -o tsv | sort
az vm list -d --query "[].[name, powerState]" -o tsv
(Optional, AWS, read-only):
export AWS_PAGER="" AWS_REGION=ca-central-1
aws sts get-caller-identity --output json
aws ec2 describe-regions --query 'Regions[].RegionName' --output text | tr '\t' '\n' | sort | head
aws ec2 describe-instances --query 'length(Reservations[].Instances[])' --output json
Cleanup: rm -rf ~/bashlab/m2. All cloud calls in this module are read-only, so there are no cloud resources to delete.

Case 1: CI job stuck for 6 hours

Problem: After upgrading to AWS CLI v2, a script running on a self-hosted runner (with a pseudo-TTY allocated) calls aws ec2 describe-instances, and its output is passed to less, so the job waits for a keypress until it times out. Fix: Set it at the top of the script export AWS_PAGER="", or in the ~/.aws/config settings cli_pager=, or add it to each command --no-cli-pager. Limitations: It only affects the CLI's own pager and does not affect API pagination.

Case 2: subscription ID had quotes, so the script acted on the default subscription by mistake

Problem:sub=$(az account list --query "[?name=='prod'].id") Got [ "…" ] (a JSON array),az account set -s "$sub" failed, but the script did not set -e, and subsequent commands ran on the current default subscription (the test subscription). Fix:① Use -o tsv and [0] to get a single value; ② validate the format [[ $sub =~ ^[0-9a-f-]{36}$ ]]; ③ pass the subscription explicitly on every command --subscription "$sub", instead of relying on the global default. Limitations: When multiple subscriptions share the same name, [0] it returns an arbitrary one; names should be unique, or use IDs instead.

Case 3: inventory script “can’t find resources” on a Windows dev machine

Problem: A developer in Git Bash calls the Windows version of az,-o tsv whose output lines each end with \r\n , and the variable value ends with \r, so the next command reports “ResourceNotFound”. Fix: Install the Linux build of az in WSL, or | tr -d '\r'; when troubleshooting, use printf '%q\n' "$var" to see $'abc\r' (verified). Limitations: When JSON output is parsed by jq \r counts as whitespace, so the impact is minor.

Common errors and fixes

The subscription of '"0000…"' doesn't exist in cloud 'AzureCloud'.

Cause: The variable holds JSON (with quotes / brackets), not a plain value.

printf '%q\n' "$sub"

Fix:--query "[0].id" -o tsv or -o json | jq -r '.[0].id'.

ERROR: argument --query: invalid jmespath_type value: …

Cause: Quotes / brackets in the query were rewritten by the shell (PowerShell especially), or jq syntax was mixed in (select(),== followed by a double-quoted string)

az vm list --query "[?powerState=='VM running'].name" -o tsv --debug 2>&1 | grep -m1 'Command arguments'

Fix: In Bash, wrap the whole query in double quotes and string literals in single quotes; or put the query in a variable q="…" then use --query "$q".

Unable to locate credentials. You can configure credentials by running "aws configure". (rc=253)

Cause: No credential source is available in the current environment (environment variables, SSO cache, config file, instance role), or the SSO token has expired.

aws configure list; aws sts get-caller-identity; echo "rc=$?"

Fix:aws sso login --profile …; in CI, use an OIDC role (Module 7). In scripts, show a “log in” hint for code 253 (see the “Commands” tab's aws_ro).

An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation (rc=254)

Cause: Credentials are valid, but the IAM policy does not allow the operation, or the region is restricted by an SCP.

aws sts get-caller-identity --query Arn --output text

Fix: Add least-privilege read-only permissions to the role (for example ec2:Describe*); confirm AWS_REGION.

In a while read loop, columns “shift”: the second column becomes the value of the third column

Cause: Tab is an IFS whitespace character,consecutive tabs are merged, so empty fields disappear.

printf 'a\t\tc\n' | while IFS=$'\t' read -r x y z; do printf '[%s][%s][%s]\n' "$x" "$y" "$z"; done   # [a][c][]

Fix: Add a placeholder for empty values in jq / JMESPath (jq: .x // "-"; JMESPath: not_null(x, '-')), or switch to @json one object per line, then parse each one individually.

Command-line exercises
1. Read all resource group names in the current Azure subscription into a Bash array rgs, and print the count.
mapfile -t rgs < <(az group list --query "[].name" -o tsv | tr -d '\r')
echo "${#rgs[@]}"
2. In ca-central-1, list all stopped instance IDs (server-side filtering), making sure the pager is not triggered.
aws ec2 describe-instances --region ca-central-1 --no-cli-pager \
  --filters Name=instance-state-name,Values=stopped \
  --query 'Reservations[].Instances[].InstanceId' --output text | tr '\t' '\n'
Scenario analysis
A nightly script that “stops all dev environment VMs” has recently started occasionally skipping some VMs, with no errors in the logs. How would you troubleshoot this?

Possible causes and how to check: ① only used the --query of [0] or --output text + --query in each page (AWS), so behavior changes as result sets grow. Switch to JSON output + jq or server-side filtering; --max-items / --no-paginate; ③ tag values differ in case (e.g. Dev vs dev), JMESPath and server-side filtering are case-sensitive; ④ empty fields in the TSV shift columns, so some VMs' names are read as empty; ⑤ some VMs are in another subscription or region. Improvements: log the “number queried” and the “number successfully processed” and alert on any mismatch; check the exit code for each VM operation; use dry-run mode to print the list first.

Verified instructional videos

▶
The Ultimate JQ Tutorial: Everything You Need to Know to Parse JSON Like a Pro — Earthly
English · jq filters, select, map, @tsv, etc. (the jq part of this module)

About az --query / aws --query (JMESPath) scripting: No verified video found (all search results are text tutorials); refer to the official docs below, and make your own video from the storyboard script.

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–15s
Visual: id=$(az … --query id) after echo $id shows a quoted value, and the next command errors.
Narration: the default output of the cloud CLI is JSON, so putting it straight into a variable keeps the quotes.
Shot 2 · 15–45s
Visual: a five-stage pipeline (API, automatic pagination, query, output, Bash), with the data blocks getting smaller at each stage.
Narration: server-side filtering reduces the data first, JMESPath picks out fields on the client, and the TSV is read line by line by Bash.
Shot 3 · 45–65s
Visual: less The pager hangs the CI log, then add AWS_PAGER="" , and the job then finishes successfully.
Narration: AWS CLI v2 enables the pager by default, so scripts must always turn it off.
Shot 4 · 65–80s
Visual: exit code signs 253, 254 and 255 light up in turn, with labels “config / server / other” beside them.
Narration: use exit codes to tell “not logged in” apart from “no permission”, and give actionable error messages.
or score ≥ 70% on the “Quiz”

Module 3 · Batch operations: parallel execution and SSH loops

13:00 – 21:00 · From “one at a time” to “parallel in groups of 8”, without losing any host's results or exit codes
8 minGNU xargs · GNU parallel 20261022 · OpenSSH★★★★☆
Learning objectives
  • Explain why while read a loop ssh only processes the first host (ssh reads the loop's stdin), and fix it with ssh -n / </dev/null .
  • Use xargs -0 -P N and GNU parallel -j N --joblog --tag to run in parallel, and understand their exit codes (xargs 123, parallel = number of failed jobs).
  • Configure batch SSH with BatchMode=yes,ConnectTimeout,StrictHostKeyChecking=accept-new, write each host's stdout, stderr and exit code to separate files, and summarize them.
  • Know when to stop writing SSH loops and switch to Ansible.
Prerequisites: Subshells and pipe scope from Lesson 2, and the find -print0 | xargs -0 from Lesson 5. Priority:★★★★☆

What: three ways to run in parallel

  • Bash background jobs: cmd & + wait (in Bash 5.1+, wait -n -p var can get the PID of the first job to finish) — no dependencies needed, but you must control concurrency yourself.
  • xargs -P N: GNU / BSD xargs both support this; it reads arguments from stdin and runs at most N child processes at a time. If any call exits with 1–125, the final xargs exit code is 123 (verified).
  • GNU parallel: the most feature-complete: --joblog (start time, duration, exit code of each job),--tag (prefixes output with the hostname), output grouped per job without interleaving,--retries,--timeout,--halt,--results directory. The exit code is the number of failed jobs (1–100); above 100 it is 101.

Why: why SSH loops go wrong

  • stdin gets eaten: while read h; do ssh "$h" uptime; done < hosts— ssh by default forwards the local stdin to the remote host, so the first call reads all the remaining lines of hosts and the loop runs only once (verified: with 3 lines, only h1 was processed).
  • Stuck at an interactive prompt: unknown host fingerprints and password prompts will make an unattended script wait forever.
  • Serial execution is too slow: 200 hosts × 3 seconds each = 10 minutes; if one host is unreachable, you also wait for the default TCP timeout.
  • Interleaved output: multiple background jobs writing to stdout at the same time mix their lines together, so you can't tell which line came from which host.

How: essentials of reliable batch execution

  1. The host list comes from a trusted source (inventory.json / cloud API), one host per line, or NUL-separated.
  2. Each task: ssh -n -o BatchMode=yes -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new, and when needed, wrap it with timeout 60.
  3. Concurrency: xargs -P or parallel -j, set based on what the target system can handle (for example, API rate limits or bastion connection counts).
  4. Results: write each host's output to results/<host>.out|.err|.rc, or use parallel's --joblog / --results; finally summarize the success / failure lists, and exit non-zero when the failure count > 0.
ApproachDependenciesConcurrency controlResult collectionBest for
& + waitNoneWrite your own semaphore (wait -n)Write your ownSmall fixed set of tasks
xargs -Pfindutils (almost always installed)-P NOnly the summary exit code (123)Simple batch jobs, containers / CI
GNU parallelRequires installation (Perl)-j N,--load,--delay--joblog,--results,--tagBatch ops work that needs reports
Ansible ad-hoc / playbookAnsibleforks,serialstructured results, idempotentConfig changes, rolling releases

When: when to switch to Ansible

Read-only inspection (version, disk, certificate expiry) is fine with an SSH loop; once you need to change state (install packages, change config, restart services) and need idempotency, a dry run (--check), rolling batches (serial) and failure-rate control, switch to Ansible.

Common misconceptions① “-P 0 Faster is better”—in GNU xargs -P 0 means “as many as possible”, which can open hundreds of SSH connections at once and trigger sshd’s MaxStartups limit (extra connections get rejected at random). ② “xargs exit code 0 means everything succeeded”—exit 0 only happens when all calls succeed, but it does not tell you which host failed, so you must record it yourself. ③ “Adding & makes it a parallel script”—without wait , the script exits early, so the results and exit code are lost. ④ “StrictHostKeyChecking=no saves effort”—it accepts tampered host keys; use accept-new (only auto-accepts first-time seen hosts; a changed known host key is still rejected).

Architecture diagram: how stdin gets eaten by ssh

hosts.txtweb-01web-02api-01 fd 0 while read -r hReads line 1: web-01child process inherits the same fd 0 ssh web-01 uptimeforwards local stdin to the remoteconsumes web-02, api-01→ the loop's next read gets EOF ssh -n …stdin ← /dev/null, so it doesn't read the loop data Commands that also “eat stdin”:ssh, docker exec -i, kubectl exec -iffmpeg, mysql, read interactive prompts Another fix: read the loop from fd 3while read -r h <&3; do … done 3< hosts
Figure 3-1: the loop and the commands in its body share the same standard input; ssh drains it

Workflow diagram: parallel batch execution with result collection

inventory.jsonjq -j '… + "\u0000"' xargs -0 -P 4or parallel -j 4 worker: ssh -n … web-01 worker: ssh -n … web-02 worker: ssh … db-01 (timeout) worker: ssh -n … api 01 results/<host>.out .err .rcor --joblog jobs.tsvsummary → failure count → exit
Figure 3-2: host list → concurrent scheduling → each task writes its own files → summarized exit code

Interactive simulator: concurrency -P vs total time and failure handling

8 hosts, each taking a different amount of time, of which db-01 is unreachable (waits for ConnectTimeout=5 before failing, rc=255). Drag the concurrency level to observe the scheduling timeline (consistent with the “start the next one as soon as a slot frees up” scheduling of xargs / parallel), the total time, and the final exit code.

Concurrency -P 1

Command cheat sheet

Command / optionPurposeKey points
xargs -0 -P 4 -n 1NUL-separated, 4 concurrent jobs, one argument per callany call with rc 1–125 → final 123; killed by a signal → 125
xargs -I{}Replacement stringImplicit -L 1 (one per line); with -0 When used together, use NUL
parallel -j 8 --joblog f --tagParallel + job log + output prefixOutput is grouped by job by default, no interleaving
parallel --timeout 60 --retries 2Job timeout / retries--timeout 200% means 2× the median runtime
parallel --halt soon,fail=10%Stop dispatching when too many fail“Circuit breaker” for rolling operations
ssh -nstdin comes from /dev/nullRequired in loops; also needed for background runs
-o BatchMode=yesDisable all interactive promptsFail immediately when a password is needed (rc 255)
-o ConnectTimeout=5Connection timeoutNo limit on command run time (use timeout)
-o StrictHostKeyChecking=accept-newAutomatically accept host keys on first connectionOpenSSH 7.6+; still rejects changed known keys
ssh host bash -s -- args < script.shRun a local script on a remote hostIn this case,you cannot add -n (the script is sent via stdin).

1. Reproduce and fix “only the first host gets processed” (actual run)

printf 'h1\nh2\nh3\n' > /tmp/hosts.txt
# sh -c 'cat >/dev/null' simulates ssh: reads and forwards stdin
while read -r h; do echo "processing $h"; sh -c 'cat >/dev/null'; done < /tmp/hosts.txt
echo ---
while read -r h; do echo "processing $h"; sh -c 'cat >/dev/null' </dev/null; done < /tmp/hosts.txt
processing h1
---
processing h1
processing h2
processing h3

2. Production-grade SSH loop (serial version)

SSH_OPTS=(-n -o BatchMode=yes -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new
          -o ServerAliveInterval=10 -o ServerAliveCountMax=3)
fail=0
while IFS= read -r host; do
  [[ -z $host || $host == \#* ]] && continue
  if out=$(timeout 60 ssh "${SSH_OPTS[@]}" "$host" 'uname -r; df -h / | tail -1' 2>&1); then
    printf '%-12s OK   %s\n' "$host" "$(tr '\n' ' ' <<<"$out")"
  else
    rc=$?; ((++fail))
    printf '%-12s FAIL rc=%s %s\n' "$host" "$rc" "$out" >&2
  fi
done < hosts.txt
((fail == 0)) || { echo "$fail host(s) failed" >&2; exit 1; }

if out=$(…); then … else rc=$?: in the first command of the else branch $? still holds the exit code of the conditional command (here, a command substitution). ((++fail)) Use pre-increment: ((fail++)) When fail=0, the expression evaluates to 0 and the exit code is 1, which triggers set -e (covered in Lesson 4). An ssh-level error (connection failure, authentication failure) exits with 255; when the remote command fails, ssh returns that command's exit code; timeout a timeout returns 124.

3. xargs parallel + per-host results saved to disk (actual run, using mockapi in place of hosts)

R=$(mktemp -d)
run_one() {   # run_one name URL results-dir
  local name=$1 url=$2 R=$3
  if curl -fsS -o "$R/$name.out" --max-time 3 "$url" 2>"$R/$name.err"; then
    echo 0 >"$R/$name.rc"
  else
    echo $? >"$R/$name.rc"
  fi
}
export -f run_one
printf '%s\t%s\n' web-01 http://127.0.0.1:8000/healthz  web-02 http://127.0.0.1:8000/status/503 \
                  "api 01" http://127.0.0.1:8000/healthz db-01 http://127.0.0.1:9/ |
  tr '\t\n' '\0\0' |
  xargs -0 -n 2 -P 4 bash -c 'run_one "$2" "$3" "$1"' _ "$R"
for f in "$R"/*.rc; do n=${f##*/}; printf '%-8s rc=%s\n' "${n%.rc}" "$(<"$f")"; done
api 01   rc=0
db-01    rc=7
web-01   rc=0
web-02   rc=22

Key points: ① bash -c '…' _ "$R" in _ occupies $0, and the two arguments xargs appends become $2 $3 ($1 the results directory); ② the function needs export -f to be available in bash -c child processes; ③ use NUL separation, so spaces in names (api 01) are not split; ④ pass task data as arguments passed in, rather than concatenated into bash -c the script string; the latter carries injection risk.

4. xargs summary exit code and timing (actual run)

printf '%s\n' /healthz /status/500 /healthz |
  xargs -P 2 -I{} curl -fsS -o /dev/null "http://127.0.0.1:8000{}"; echo "xargs rc=$?"
time (printf '%s\n' 1 2 3 4 5 6 | xargs -P 3 -I{} curl -fsS -o /dev/null "http://127.0.0.1:8000/slow?sec=1&p={}")
curl: (22) The requested URL returned error: 500
xargs rc=123
real	0m2.031s

6 tasks, each taking 1 second, 3 running concurrently → about 2 seconds.

5. GNU parallel version (example, requires installing parallel)

jq -r '.[] | select(.env=="prod") | .ip' ~/bashlab/data/inventory.json > prod-hosts.txt
parallel -j 8 --tag --timeout 60 --joblog jobs.tsv \
  ssh -n -o BatchMode=yes -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new {} \
      "'uptime -p; systemctl is-active myapp || true'" :::: prod-hosts.txt
echo "failed jobs=$?"
column -t -s $'\t' jobs.tsv | head        # Seq Host Starttime JobRuntime Send Receive Exitval Signal Command
awk -F'\t' 'NR>1 && $7!=0 {print $NF}' jobs.tsv   # command lines of failed jobs
10.0.1.11	up 3 days, 2 hours
10.0.1.11	active
10.0.1.12	up 3 days, 2 hours
10.0.1.12	active
ssh: connect to host 10.0.3.31 port 22: Connection timed out
failed jobs=1

The first time parallel runs, it prints a citation notice; after an interactive run parallel --citation , it no longer prompts. In scripts / CI, the notice goes to stderr and does not affect results. :::: means reading arguments from a file,::: means passing arguments directly.

6. Pure Bash: background jobs + concurrency cap (no dependencies)

max=4; pids=(); fail=0
for host in "${hosts[@]}"; do
  ssh -n -o BatchMode=yes -o ConnectTimeout=5 "$host" uptime >"out/$host.log" 2>&1 &
  pids+=($!)
  while (( $(jobs -rp | wc -l) >= max )); do
    wait -n || ((++fail))           # Bash 4.3+: wait for any one to finish
  done
done
for p in "${pids[@]}"; do wait "$p" 2>/dev/null || ((++fail)); done
echo "fail=$fail"

This approach is weak at tracking “who failed” (wait -n an already reaped PID, if you wait on it again, wait returns 127, which may double-count); for accurate reporting, use Bash 5.1+'s wait -n -p pid to record PIDs, or just use xargs / parallel.

Lab: parallel health check of servers

Zero cost: use mockapi to simulate the hosts' “/healthz”, and use localhost to simulate an SSH target (optional).

Generate host inventory: take the prod host names from inventory.json, and map each one to a simulated URL (one of them deliberately points to 503, one to a closed port).
mkdir -p ~/bashlab/m3 && cd ~/bashlab/m3
jq -r '.[].name' ~/bashlab/data/inventory.json 2>/dev/null | head -6 > names.txt || true
[[ -s names.txt ]] || printf '%s\n' web-01 web-02 api-01 db-01 cache-01 "batch 01" > names.txt
i=0
while IFS= read -r n; do
  case $((i++ % 4)) in
    2) url="http://127.0.0.1:8000/status/503" ;;
    3) url="http://127.0.0.1:9/healthz" ;;
    *) url="http://127.0.0.1:8000/slow?sec=1" ;;
  esac
  printf '%s\t%s\n' "$n" "$url"
done < names.txt > targets.tsv
cat targets.tsv
Serial baseline:
time while IFS=$'\t' read -r n url; do
  curl -fsS -o /dev/null --max-time 3 "$url" && echo "OK $n" || echo "FAIL $n"
done < targets.tsv

Roughly equal to the sum of each task's duration (each slow one 1 second).

Parallel version + results saved to disk:
rm -rf results && mkdir results
check() {  # check results-dir name URL
  local R=$1 n=$2 url=$3 code rc=0
  code=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 3 "$url" 2>"$R/$n.err") || rc=$?
  printf '%s\t%s\t%s\n' "$n" "$code" "$rc" > "$R/$n.tsv"
  [[ $rc == 0 && $code == 200 ]]
}
export -f check
time (tr '\t\n' '\0\0' < targets.tsv | xargs -0 -n 2 -P 4 bash -c 'check "$1" "$2" "$3"' _ results)
echo "xargs rc=$?"
cat results/*.tsv | sort | column -t -s $'\t'
real	0m1.0xs
xargs rc=123
api-01    503  0
batch 01  200  0
cache-01  200  0
db-01     000  7
web-01    200  0
web-02    200  0
Summary and exit code: write a summary that exits 1 on failure:
awk -F'\t' '$2!=200 || $3!=0 {bad++; print "FAIL", $1, "http="$2, "curl_rc="$3} END {exit bad>0}' results/*.tsv
echo "summary rc=$?"
(Optional) SSH to localhost: after completing step 5 of Module 0:
printf '%s\n' localhost localhost 127.0.0.1 > ssh-hosts.txt
xargs -P 3 -I{} ssh -n -o BatchMode=yes -o ConnectTimeout=5 {} 'echo "$(hostname) $(date +%T)"' < ssh-hosts.txt
Cleanup: rm -rf ~/bashlab/m3; if you enabled sshd for this lab and no longer need it: sudo systemctl disable --now ssh.

Case 1: certificate check “only checked one host”

Problem: The weekly TLS certificate expiry check script calls while read inside ssh "$h" openssl x509 …, and for three years it has only checked the first host on the list. One edge server's certificate expired and caused an outage. Fix:ssh -n; at the end, the script prints “checked N hosts / M in inventory” and raises an alert if the numbers differ. Limitations: This kind of “silently skipped” failure is hard to catch in testing, so you must rely on count verification.

Case 2: -P 0 overwhelmed the jump host

Problem: Running 800 hosts through one jump host (ProxyJump) with xargs -P 0 ssh …, the jump host's sshd defaults to MaxStartups 10:30:100, so many connections are randomly dropped during authentication, and the script reports 300 hosts as “unreachable”. Fix: Set concurrency to 20; enable SSH connection multiplexing (ControlMaster auto,ControlPersist 5m); for failed tasks, use parallel --retries 2 to retry. Limitations: The control socket directory for connection multiplexing requires strict permissions (for example ~/.ssh/cm-%C).

Case 3: circuit breaker for rolling restarts

Problem: The script that restarts services in batches failed to restart all 50 hosts when the new config had an error. Fix:parallel -j 5 --halt soon,fail=2: stop dispatching new tasks after 2 failures; a better approach is Ansible's serial + max_fail_percentage, or run it on one canary host first. Limitations:--halt Tasks already run are not rolled back; you need to design rollback yourself (see Module 4).

Common errors and fixes

The loop only processed the first host, with no errors at all

Cause: The ssh inside the loop body (or docker exec -i,mysql etc.) read the loop's stdin.

bash -x ./batch.sh 2>&1 | grep -c '+ ssh'

Fix:ssh -n or </dev/null; or read the loop from fd 3: while read -r h <&3; do …; done 3< hosts.txt.

Host key verification failed. / the script hangs at “Are you sure you want to continue connecting (yes/no)?”

Cause: The host is being connected to for the first time, or its host key has changed; without BatchMode , it waits for interactive input.

ssh-keygen -F web-01; ssh -o BatchMode=yes web-01 true; echo "rc=$?"

Fix: New host: -o StrictHostKeyChecking=accept-new or collect the key in advance with ssh-keyscan and verify the fingerprint; for a changed key, after confirming the host was reinstalled, run ssh-keygen -R web-01. Do not use StrictHostKeyChecking=no + UserKnownHostsFile=/dev/null.

xargs: bash: terminated by signal 13 / output lines get interleaved

Cause: A downstream command (such as head) closed the pipe early, so the child process received SIGPIPE; or multiple parallel tasks wrote directly to the same stdout.

… | xargs -P 4 … > all.log   # lines may interleave

Fix: Each task writes its own file, and you merge them at the end; or use GNU parallel (it groups output by job by default,--line-buffer keeping each line intact).

ssh: connect to host 10.0.3.31 port 22: Connection timed out (each host waited 2 minutes)

Cause: You did not set ConnectTimeout, so the system TCP connection timeout applies (Linux default retransmission is about 2 minutes).

Fix:-o ConnectTimeout=5; for command run time, use timeout 60 ssh … (ConnectTimeout only governs the connection phase).

bash: run_one: command not found (calling a function inside xargs / parallel)

Cause: xargs starts a new process, which cannot see the functions in the current shell.

Fix:export -f run_one then use bash -c 'run_one "$@"' _; GNU parallel also needs export -f, or use env_parallel.

Command-line exercises
1. Use xargs with 5 concurrent jobs to run hosts.txt on each host listed in uptime, with no interactive prompts, a 5-second connect timeout, and a 30-second total timeout per host.
xargs -P 5 -I{} timeout 30 ssh -n -o BatchMode=yes -o ConnectTimeout=5 {} uptime < hosts.txt
2. Do the same with GNU parallel, with output prefixed by hostname, and write the job log to jobs.tsv.
parallel -j 5 --tag --timeout 30 --joblog jobs.tsv ssh -n -o BatchMode=yes -o ConnectTimeout=5 {} uptime :::: hosts.txt
Scenario analysis
You need to change a config item from A to B on 300 hosts and restart the service, and a colleague plans to write parallel -j 50 ssh {} 'sed -i … && systemctl restart app'. What would you recommend?

This is a high-risk, state-changing batch operation: ① no dry run or idempotency (re-running sed may replace a second time); ② 50 concurrent restarts could cause capacity to drop sharply; ③ no rollback after failure. Recommendation: prefer Ansible (lineinfile/template idempotent,--check --diff dry run,serial: 10% batching,max_fail_percentage circuit breakers, handlers that restart only on change). If you must use Shell: first run it on 1 canary host and verify the health check; parallel -j 10 --halt soon,fail=1 --joblog write commands to be idempotent (check with grep first); run a health check after each host; keep a backup of the old config for rollback.

Verified instructional videos

▶
Part 1: GNU Parallel script processing and execution — Ole Tange
English · Episode 1 of the official introductory series by the GNU parallel author
▶
Xargs Should Be In Your Command Line Toolbag — DistroTube
English · xargs basics (-I, -n, -P)

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: hosts.txt's three lines flow into a while loop, and ssh sucks up the remaining two lines like a vacuum cleaner.
Narration: ssh inside the loop reads standard input, so only the first host gets processed. Adding -n fixes it.
Shot 2 · 20–50s
Visual: a Gantt chart; concurrency is dragged from 1 to 4 and the total-duration bar gets shorter; the db-01 bar is red.
Narration: xargs -P and parallel -j control concurrency. Unreachable hosts must fail fast via ConnectTimeout.
Shot 3 · 50–80s
Visual: the results directory has one rc file per host; two rows in the summary table turn red, and the script exits with code 1.
Narration: each host's result is saved separately and summarized at the end; any failure returns a non-zero code so the scheduler knows.
or score ≥ 70% on the “Quiz”

Module 4 · Deployment scripts: health checks, rollback and atomic switching

21:00 – 28:00 · releases/ + current symlink: switch with a single rename(2), and if the health check fails, rename back
7 minGNU coreutils ln / mv -T · rename(2)★★★★★
Learning objectives
  • Explain the structure and benefits of the “releases/<timestamp> + current symlink” deployment pattern (second-level rollback, traceable old versions, and services never reading half-finished files during deployment).
  • Use ln -sfn target .current.tmp + mv -Tf .current.tmp current to implement an atomic switch, and explain why rm current; ln -s … rm-then-recreate and -T ln -s without -n mv are both wrong (this module has measured data).
  • Run health checks after the switch (with retries and timeouts); on failure, automatically roll back to the previous version and notify the caller (CI / a person) with a non-zero exit code.
  • Add a deployment lock (flock), version validation, and old-version cleanup (keep N versions and never delete current).
Prerequisites: The health checks from Module 1, and trap / flock from Lesson 4. Priority:★★★★★

What: directory layout

~/bashlab/deploy/
├── releases/
│   ├── 20261117T070539Z/     ← v1.0.0 (complete, read-only release directory)
│   ├── 20261117T070540Z/     ← v1.1.0
│   └── 20261117T070541Z/     ← v1.2.0 (health check failed; kept for troubleshooting)
├── current -> releases/20261117T070540Z     ← services access code only through this
├── shared/                   ← shared across versions: logs, uploads, .env (linked into releases with symlinks as needed)
└── .deploy.lock              ← deployment lock (this module's standalone script; opsctl v0.3 uses util::lock → ~/bashlab/opsctl/var/lock/deploy.lock)

The web server / systemd unit only references the current path (for example WorkingDirectory=/srv/app/current, nginx root /srv/app/current/public;). Deployment = prepare a new directory and repoint one symlink. Capistrano, Deployer and other tools have used exactly this pattern for years.

Why: why “atomic” matters

  • In-place overwrite (tar -x extract directly into the running directory / rsync overwrite): during extraction the service can read a mix of old and new files; a mid-way failure leaves a half-finished version, and rollback means redeploying the old package.
  • Delete-then-create (rm current && ln -s new current): between the two system calls, current the path does not exist, so requests get 404 / 500. In this module's test, we looped the switch while sending 400 concurrent requests, and 132 requests got 404.
  • Atomic replacement: POSIX rename(2) guarantees that when the new path already exists, it is atomically replaced—at any moment, access to current, either sees the old target or the new one, and never “does not exist”. The same test: 400 requests all returned 200.

How: system calls for switching and rolling back

  1. mkdir releases/$ts + tar -xzf package -C releases/$ts: the new version is fully written to disk (the service cannot see it).
  2. Validation: must contain version.txt and other key files; optionally run releases/$ts/bin/check.
  3. ln -sfn releases/$ts .current.tmp Switch: symlink(2) in the temp name, create a new link (-n-n: if .current.tmp already exists and points to a directory, do not follow into it)
  4. mv -Tf .current.tmp current: rename(2) atomic replacement. -T (--no-target-directory) is critical: current current is a symlink pointing to a directory, so without -T , mv treats it as a target directory, moving .current.tmp inside the old release (verified: current still points to the old version, and the old directory gained an extra .tmp2).
  5. Health check (with retries + timeout). On failure → re-run steps 3 and 4 against the old target → exit code 1.
  6. Cleanup: sort releases by name, keep the most recent N, and skip the one current points to.
ApproachAtomic switch?Rollback speedNotes
In-place overwrite (tar / rsync into the running directory)NoSlow (redeploy)Simplest, but also the most dangerous
rm + ln -sNo (has a window)FastMeasured: 33% of requests got 404
ln -sfn Temp name + mv -TYesSecondsUsed in this lesson
Blue-green (two sets of instances + load balancer switch)Yes (at the LB layer)SecondsRequires double the resources; see the CI/CD and K8s courses
Container rolling update (K8s Deployment)Pod by podkubectl rollout undoHandled by the platform; see the Kubernetes course

When: scope and limitations

Suitable for “file-based” releases on a single machine or a small number of hosts: static sites, PHP / Python / Node application directories, config bundles, binary tools. Limitations: ① long-running processes that already have old files open won't switch automatically; they need a systemctl reload / restart (for example, gunicorn's HUP), or the app reopens files via the path on every request; ② database migrations cannot be rolled back with a symlink, so migrations must be backward-compatible (expand first, contract later); ③ if a process's working directory is current resolved to the real directory, it stays in the old directory after the switch.

Common misconceptions① “ln -sfn new current a single command is atomic”—its semantics are “delete the existing target, then create”; across implementations / versions it may be two steps (unlink + symlink) with a window. Do not rely on this; explicitly use a temp name + mv -T. ② “mv -f tmp current is enough”—when current points to a directory, it moves tmp into that directory. ③ “Running the health check before the switch is enough”—the new version receives no traffic before the switch at all; do a “pre-check” (files, config syntax) before the switch and a “health check” after it; you need both. ④ “Rolling back is just redeploying the old package”—that is a redeploy, which is slow and can fail; a symlink rollback needs only one rename. ⑤ On macOS, the BSD mv has no -T, use mv -h (does not follow the target symlink) or Homebrew gmv -T.

Architecture diagram: directories and request paths before and after deployment

HTTP requestnginx / http.server current (symlink)resolved each time a file is opened releases/…539Z · v1.0.0 releases/…540Z · v1.1.0 (current) releases/…541Z · v1.2.0 (failed) switch → health check fails rollback shared/logs/ uploads/ .envSymlink inside a releasepoints here, preserved across versionsRollback does not affect data
Figure 4-1: services access code only through current; switching and rolling back both change only where current points

Sequence diagram: atomic switch vs delete-then-create

rm current; ln -s new current (non-atomic) current → old (request 200) does not exist (404) current → new (request 200) unlink(2)symlink(2) ln -sfn new .current.tmp; mv -Tf .current.tmp current (atomic) current → old (meanwhile .current.tmp → new is ready) current → new rename(2): one system call; the old link is replaced atomically Measured (Bash 5.2 + python http.server, 400 concurrent requests during the loop switch): non-atomic 268×200 + 132×404; atomic 400×200
Figure 4-2: comparing the “window” of the two switch methods

Core animation (below): the deployment script's atomic switch and rollback

Pick a scenario and step through each stage of the deployment script: which system call runs, what changes on the file system, and which version an incoming request sees at that moment. The terminal below shows the script's actual output (measured logs from this module's lab) and the corresponding system calls.

RequestGET /version.txt current .current.tmp releases/…539Z · v1.0.0 releases/…540Z · v1.1.0 releases/…541Z · v1.2.0 Health check—Service version —
Ready.
$ cd ~/bashlab/m4

Command cheat sheet

CommandPurposeKey points
ln -sfn target linkCreate / replace a symlink-n: if the link already exists and points to a directory, don't follow into it
mv -Tf source targetRename and atomically replace-T: treat the target as a regular file; within the same file system, this is rename(2)
readlink link / readlink -fRead the link target / fully resolveRelative link releases/… easier to relocate as a whole
flock -n 9Acquire the deployment lock without blockingTwo deployments running at once = disaster
date -u +%Y%m%dT%H%M%SZSortable UTC timestampSorting by name = sorting by time
systemctl reload appMake long-running processes load new codeDepends on the app (gunicorn HUP, php-fpm reload)

1. Measured: without -T, mv moves the link into the old directory

mkdir -p releases/a releases/b
ln -sfn releases/a current
ln -s releases/b .tmp2; mv -f .tmp2 current       # wrong: current points to a directory
ls -l current; ls -A releases/a
ln -s releases/b .tmp3; mv -Tf .tmp3 current      # correct
ls -l current
lrwxrwxrwx 1 root root 10 Nov 17 02:05 current -> releases/a
.tmp2
lrwxrwxrwx 1 root root 10 Nov 17 02:05 current -> releases/b

2. Minimal rollback-capable deployment script deploy.sh

#!/usr/bin/env bash
# deploy.sh — minimal rollback-capable deployment: releases/<ts> + current symlink
# Usage: deploy.sh <package.tar.gz> [health check URL]
set -Eeuo pipefail
ROOT=${ROOT:-$HOME/bashlab/deploy}
pkg=${1:?Usage: deploy.sh package.tar.gz [URL]}
url=${2:-}

switch() {   # atomic switch: create a temp link first, then overwrite current with rename(2)
  ln -sfn -- "$1" "$ROOT/.current.tmp"
  mv -Tf -- "$ROOT/.current.tmp" "$ROOT/current"
}
healthy() {  # up to 3 tries, 2-second timeout each, with 1s and 2s intervals
  local i
  for i in 1 2 3; do
    curl -fsS -o /dev/null --max-time 2 "$url" && return 0
    ((i < 3)) && sleep "$i"
  done
  return 1
}

ts=$(date -u +%Y%m%dT%H%M%SZ)
rel="releases/$ts"
mkdir -p -- "$ROOT/$rel"
tar -xzf "$pkg" -C "$ROOT/$rel"
[[ -f $ROOT/$rel/version.txt ]] || { echo "package is missing version.txt" >&2; rm -rf -- "${ROOT:?}/$rel"; exit 1; }

prev=$(readlink -- "$ROOT/current" 2>/dev/null || true)
switch "$rel"
echo "switched: current -> $rel (prev: ${prev:-none}, version $(<"$ROOT/$rel/version.txt"))"

if [[ -n $url ]] && ! healthy; then
  if [[ -n $prev ]]; then
    switch "$prev"
    echo "health check FAILED, rolled back: current -> $prev" >&2
  else
    echo "health check FAILED, nothing to roll back to" >&2
  fi
  exit 1
fi
echo "deploy OK: $rel"

Key points: ① ! healthy is in a conditional context,healthy failures inside it do not trigger set -e; ② healthy the loop's last ((i < 3)) evaluates to false,&& a failing non-final command in a list does not trigger errexit; ③ ${ROOT:?} prevents ROOT from being empty when rm -rf /releases/…; ④ relative links releases/$ts let the whole deployment directory be relocated / mounted elsewhere. The production version (locks, cleanup, logs, manual rollback) is in Module 8's lib/cmd_deploy.sh.

3. Make long-running processes aware of new versions

# Reference current in the systemd unit (the path is resolved when the process starts)
#   WorkingDirectory=/srv/myapp/current
#   ExecStart=/srv/myapp/current/venv/bin/gunicorn app:app
#   ExecReload=/bin/kill -HUP $MAINPID
switch "releases/$ts" && sudo systemctl reload-or-restart myapp.service

On receiving HUP, gunicorn reloads its config and starts new workers (new workers import code from the new path; if using preload_app a full restart is required). Check your application server's docs for details. This lesson's lab uses python3 -m http.server -d current: it opens files by path on every request, so the switch takes effect immediately (verified).

Lab: deploy 3 versions locally and trigger automatic rollback

Zero cost: the deployment target is ~/bashlab/deploy, served by Python's built-in http.server.

Build 3 release packages (v1.2.0 deliberately lacks healthz, simulating a “bad version”):
mkdir -p ~/bashlab/m4/build && cd ~/bashlab/m4
for v in 1.0.0 1.1.0 1.2.0; do
  d=build/$v; mkdir -p "$d"
  echo "$v" > "$d/version.txt"
  echo "<h1>myapp $v</h1>" > "$d/index.html"
  [[ $v != 1.2.0 ]] && echo ok > "$d/healthz"
  tar -czf "app-$v.tar.gz" -C "$d" .
done
ls *.tar.gz
app-1.0.0.tar.gz
app-1.1.0.tar.gz
app-1.2.0.tar.gz
Save the script and start the “service”: copy the script from the “Commands” tab deploy.sh and save it to ~/bashlab/m4/deploy.sh, then:
chmod +x deploy.sh
mkdir -p ~/bashlab/deploy
python3 -m http.server 8080 --bind 127.0.0.1 -d ~/bashlab/deploy/current >/dev/null 2>&1 &
echo $! > http.pid

At this point current does not exist yet, so requests return 404 — exactly the state before the first deployment.

Deploy v1.0.0 and v1.1.0:
./deploy.sh app-1.0.0.tar.gz http://127.0.0.1:8080/healthz; echo "rc=$?"; sleep 1
./deploy.sh app-1.1.0.tar.gz http://127.0.0.1:8080/healthz; echo "rc=$?"
curl -s http://127.0.0.1:8080/version.txt
switched: current -> releases/20261117T070539Z (prev: none, version 1.0.0)
deploy OK: releases/20261117T070539Z
rc=0
switched: current -> releases/20261117T070540Z (prev: releases/20261117T070539Z, version 1.1.0)
deploy OK: releases/20261117T070540Z
rc=0
1.1.0

sleep 1: timestamps are precise to the second, so two deployments within the same second will collide (Module 8's version detects this and reports an error).

Deploy bad version v1.2.0 and observe the automatic rollback:
./deploy.sh app-1.2.0.tar.gz http://127.0.0.1:8080/healthz; echo "rc=$?"
curl -s http://127.0.0.1:8080/version.txt
ls -l ~/bashlab/deploy; ls ~/bashlab/deploy/releases
switched: current -> releases/20261117T070541Z (prev: releases/20261117T070540Z, version 1.2.0)
health check FAILED, rolled back: current -> releases/20261117T070540Z
rc=1
1.1.0
lrwxrwxrwx current -> releases/20261117T070540Z
drwxr-xr-x releases
20261117T070539Z
20261117T070540Z
20261117T070541Z

The bad version's directory is kept for troubleshooting (“why is there no healthz?”). Module 8's cleanup logic will delete it by the retention count in later deployments.

Verify “zero window”: keep switching nonstop while sending concurrent requests, and tally the status codes:
cd ~/bashlab/deploy
mapfile -t R < <(ls releases | head -2)
( for i in $(seq 400); do curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/version.txt; done | sort | uniq -c ) &
for i in $(seq 200); do
  for r in "${R[@]}"; do ln -sfn "releases/$r" .t; mv -Tf .t current; done
done; wait
echo "--- control group: rm + ln"
( for i in $(seq 400); do curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/version.txt; done | sort | uniq -c ) &
for i in $(seq 300); do rm -f current; ln -s "releases/${R[0]}" current; done; wait
ln -sfn "releases/${R[1]}" .t && mv -Tf .t current     # restore to v1.1.0
    400 200
--- control group: rm + ln
    268 200
    132 404
Cleanup:
kill "$(cat ~/bashlab/m4/http.pid)"
rm -rf ~/bashlab/deploy    # Module 8 redeploys; keep the packages under ~/bashlab/m4

Case 1: 502 spikes during deployment

Problem: A PHP site got 502s for a few seconds on every deployment: the script first rm -rf /var/www/app then git clone. Fix: Switched to releases/ + current; nginx root points to root /var/www/app/current/public;, and php-fpm uses $realpath_root to pass the script path (avoids OPcache caching the old symlink path); after switching, systemctl reload php-fpm. Limitations: OPcache / application-level caches need to be cleared separately or reloaded.

Case 2: code was rolled back but the database was not

Problem: The v2 migration dropped a column; after the health check failed, the script switched current back to v1, and v1 errored when reading that column, widening the outage. Fix:“Expand first, contract later” (expand/contract): v2 only adds columns and remains compatible with the old code; v3 drops the old column only after v2 is confirmed stable; the deployment script treats the “migration” as a separate, approvable step. Limitations: Symlink rollback only covers code and static files.

Case 3: releases filled the disk

Problem: More than ten deployments a day with no cleanup; releases filled the disk, so the next deployment tar failed, and the script did not set -e, and switched to a half-extracted directory. Fix: Strict mode; verify key files after extraction; keep the most recent 5 releases and never delete current or the previous version; check free space before deploying (df --output=avail). Limitations: The cleanup logic itself also needs testing (Module 8 / bats from Lesson 7).

Common errors and fixes

After switching, current still points to the old version, and an extra .current.tmp appears in the old version's directory

Cause: Used mv -f instead of mv -Tf; current is a symlink to a directory, so it was treated as the target directory.

ls -lA "$(readlink -f current)" | grep current.tmp

Fix:mv -Tf (GNU); on macOS, use mv -h or gmv -T; delete the file that was moved in by mistake.

ln: failed to create symbolic link 'current/releases': File exists (or the link was created inside the release directory)

Cause: Running directly against current ln -sf without -n, ln followed the symlink to a directory and created the link inside that directory.

Fix: Always use ln -sfn, and on the temp name, then run mv -T.

The health check passed, but users still see the old version

Cause: A long-running process resolved current at startup (working directory or already-imported modules), so switching the link has no effect on it; or CDN / browser caching.

readlink /proc/$(systemctl show -p MainPID --value myapp)/cwd

Fix: Reload / restart the service after switching; have the health check return the version number (/version), and the script compares “expected version == actual version”.

lock busy: …/var/lock/deploy.lock (another opsctl running?) / two CI jobs deploying at the same time caused current to point to the wrong version

Cause: Concurrent deployments. Without a lock, two scripts interleave, the one that finishes last “wins”, and the health check may be checking the other deployment's version.

Fix: In the standalone script, use exec 8>"$ROOT/.deploy.lock"; flock -n 8 || exit 1; in opsctl, use util::lock deploy (Lesson 4); in CI, also use concurrency groups (GitHub Actions concurrency:, GitLab resource_group:, see Module 7).

Command-line exercises
1. Atomically switch /srv/app/current to releases/20261117T120000Z.
cd /srv/app
ln -sfn releases/20261117T120000Z .current.tmp
mv -Tf .current.tmp current
2. List the old releases that should be cleaned up: keep 5 by name in reverse order, excluding the directory current points to.
cur=$(basename "$(readlink current)")
ls -1 releases | sort -r | tail -n +6 | grep -vxF "$cur"
Scenario analysis
The deployment script's health check only makes one request to /healthz, which occasionally fails right after a new version starts and triggers a rollback (“false rollback”). How would you improve it?

① After switching, wait for the service to become ready (readiness), e.g. probe every 1–2 seconds for up to 30 seconds, with exponential backoff and an overall time cap (this lesson's cmd::health -r); ② distinguish liveness and readiness in the health endpoint, and check dependencies (database, cache); ③ compare the returned version number to prevent “an old process answering the health check”; ④ require N consecutive successes before passing, to avoid a lucky pass; ⑤ log each probe's status code and duration, and write them to the logs / CI summary on rollback.

Verified instructional videos

No verified video found that specifically covers “atomic symlink switch deployments”. The following is related background video (title and channel verified via YouTube oEmbed):

▶
Bash in 100 Seconds — Fireship
English · about 2 minutes · quick review of Bash scripting (not the topic of this module)

Official documentation

Video storyboard script (about 100 seconds)

This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: on the server rm -rf app; tar -x, while the request stream shows red 502s.
Narration: both in-place overwriting and delete-then-create make users run into a “window”.
Shot 2 · 20–50s
Visual: in the releases directory, three version boxes, with the current arrow pointing at the middle one; a new box “grows” out of the package, with a dashed arrow from .current.tmp pointing at it.
Narration: the new version is fully written to disk first, then a new symlink is created on the temp name.
Shot 3 · 50–70s
Visual: rename makes a “click” sound, the current arrow instantly jumps to the new box; the request stream stays green.
Narration: a single rename system call atomically replaces the link. current always exists.
Shot 4 · 70–100s
Visual: three red lights from the health check, the arrow jumps back to the old version, and the terminal prints rolled back and rc=1.
Narration: if the health check fails, do one more rename to go back to the previous version, and notify the pipeline with a non-zero exit code.
or score ≥ 70% on the “Quiz”

Module 5 · Backup and rotation scripts

28:00 – 35:00 · A proper backup = complete write (temp file + atomic rename) + verifiable + restorable + automatic rotation + no concurrent runs
7 minGNU tar · sha256sum · find · flock★★★★☆
Learning objectives
  • Write a script that “never leaves a half-written backup”: first write .part a temp file, and after verification, move it mv to the final name; use trap … EXIT to clean up failure leftovers.
  • Generate and verify sha256 checksums; run a restore drill (extract into a temp directory + diff -r).
  • Implement two rotation schemes: by count (sort -z -r | tail -z -n +N) and by age (find -mtime +N), and understand the GFS (grandfather-father-son) scheme.
  • Use flock -n to prevent two backups from running at the same time; correctly handle filenames containing spaces, newlines, or a leading dash.
Prerequisites: trap and lock from Lesson 4, and the find -print0 from Lesson 5. Priority:★★★★☆

What: the lifecycle of one backup

Select source → lock → pack and compress into a temp file → verify the archive is readable → atomically rename to the final file with a UTC timestamp → generate checksum → (optional) copy off-site → rotate and delete expired backups → release lock → output the result and express success or failure with the exit code.

Why: the most common ways script backups fail

  • Half-finished backup: when the disk fills or the process is killed,tar -czf final.tar.gz leaves a truncated file with a “normal” name, and rotation logic will then delete a good older backup because of it.
  • Cannot restore: a restore drill was never run; archive corruption, missing permission info, and absolute paths all go unnoticed until you actually need the backup.
  • Rotation deletes the wrong files: ls -t | tail -n +8 | xargs rm hits a filename with spaces and deletes the wrong file; or find /backups -mtime +7 -delete once backups have stopped for 7 days,it deletes every backup.
  • Overlapping runs: the previous backup hasn't finished when cron starts another one, and the two processes compete for disk and the same filename.

How: key implementation details

  1. Timestamp: date -u +%Y%m%dT%H%M%SZ— UTC avoids duplicate names or misordering caused by daylight saving time; lexical order = time order, so rotation only needs to sort by name.
  2. Relative-path archive: tar -C parent-dir -czf … -- dir-name, so restores never write to absolute paths; -- prevents names starting with - from being treated as options.
  3. Temp file in the same directory: mktemp "$dest/.name.XXXXXX.part", ensuring mv is a rename(2) within the same file system (a cross-file-system mv degrades to “copy + delete”, which is not atomic).
  4. Verification: tar -tzf check that the archive is readable; sha256sum write .sha256, and after copying off-site, use sha256sum -c to verify the transfer is complete.
  5. Rotation: rotate only after confirming this backup succeeded; count-based rotation is safer than age-based rotation (if a backup is interrupted, it won't delete all the old backups).
Rotation policyImplementationProsRisks
By count (keep the newest N)find … -print0 | sort -z -r | tail -z -n +$((N+1))Even if backups stop, it won't delete everythingCoverage span changes when frequency changes
By age (delete backups older than N days)find … -mtime +N -deleteSimple and intuitiveDeletes everything if backups fail for a long time; -mtime the rounding rules are easy to misread
GFS (7 daily + 4 weekly + 12 monthly)Classify by date, then keep each class by countLong time span, controllable countComplex logic; consider restic / borg's forget --keep-daily …
Object storage lifecycleS3 Lifecycle / Azure Blob lifecycle managementRun by the platform, no script neededRequires a cloud account; watch minimum storage duration charges

When: boundaries of shell backup scripts

Suitable for: config directories, small data directories, export files (pg_dump 's output), log archives. Live database files should not be tarred directly (needs the database's own consistent backup tool or snapshots); for large-scale, deduplicated, encrypted, or incremental backups, use restic, BorgBackup, or your cloud provider's backup service.

Common misconceptions① “Having a backup file means you can restore”—a backup that has never had a restore drill doesn't count. ② “-mtime +7 means 7 days ago”—find rounds time down to whole 24-hour periods,+7 means “at least 8 full days ago”. ③ “ls | tail | xargs rm is enough”—filenames containing spaces or newlines make it delete the wrong file; use NUL separation. ④ “Gzipping makes it safe”—compression is not encryption; backups that contain keys should be age / gpg encrypted before they leave the host.

Workflow diagram: one backup run

flock -nFailure → exit 1 tar -czf .parttrap removes leftovers tar -tzfArchive readable? mv → final namerename(2) sha256sum.sha256 RotationKeep newest N Failure pathtar failure / disk full → set -e exits → trap deletes .partThe final name never appears, so rotation does not run Optional: off-site copyrsync -a to another host / az storage blob upload / aws s3 cpPeer runs sha256sum -c to verify; in the cloud, use a lifecycle policy for remote rotation
Figure 5-1: only a complete, checksum-verified backup gets its “final name”; rotation looks only at final names

Data flow diagram: count-based rotation via NUL pipeline

find -print0…0823Z ␀ …0826Z ␀…0824Z ␀ …0825Z ␀(order not guaranteed) sort -z -r0826Z 0825Z0824Z 0823Znew → old tail -z -n +4skip the first 3 (keep=3)→ 0823Z while read -d ''rm -f -- "$old"rm -f -- "$old.sha256" The whole pipeline is NUL-separated (␀): no filename (spaces, newlines, leading dashes) gets split or treated as an option
Figure 5-2: sort by the timestamp in the filename, rather than relying on mtime

Interactive demo: rotation window (by count / by age / GFS)

Simulates one backup per day at 02:00 starting 2026-10-01 for 60 days; you can make the backups on days 41–50 “fail” (e.g. disk full). Observe which backups each of the three policies keeps at the end of day 60. Green = kept, grey = deleted, red = that day's backup failed (no file).

N = 7

Command cheat sheet

CommandPurposeKey points
tar -C dir -czf out.tar.gz -- nameArchive with relative paths--one-file-system,--exclude=PATTERN; zstd: --zstd
tar -tzf f / tar -xzf f -C dirList / extractRestore drill: extract to a temp directory
sha256sum f > f.sha256 / sha256sum -cChecksumGenerated in the backup directory; filenames are relative paths
find d -maxdepth 1 -name 'x-*' -print0List backupsUse with sort -z,tail -z,read -d '' together
find d -name 'x-*' -mtime +7 -deleteDelete by age in daysFirst use -print to dry-run
flock -n 9Prevent concurrent runsexec 9>lockfile Open fd
rsync -a --partial src/ host:dst/Off-site copyOn the remote end, then sha256sum -c

1. Complete backup.sh

#!/usr/bin/env bash
# backup.sh — archive directory + checksum + rotation
# Usage: backup.sh <source-dir> [dest-dir] [keep-count]
set -Eeuo pipefail
src=${1:?Usage: backup.sh source-dir [dest-dir] [keep-count]}
dest=${2:-$HOME/bashlab/backups}
keep=${3:-7}

[[ -d $src ]] || { echo "Not a directory: $src" >&2; exit 2; }
src=$(cd -- "$src" && pwd)
name=$(basename -- "$src")
mkdir -p -- "$dest"

exec 9>"$dest/.backup.lock"
flock -n 9 || { echo "Another backup is already running" >&2; exit 1; }

ts=$(date -u +%Y%m%dT%H%M%SZ)
final="$dest/$name-$ts.tar.gz"
tmp=$(mktemp "$dest/.$name.XXXXXX.part")
trap 'rm -f -- "$tmp"' EXIT

tar -C "$(dirname -- "$src")" -czf "$tmp" -- "$name"
tar -tzf "$tmp" >/dev/null
mv -f -- "$tmp" "$final"
(cd -- "$dest" && sha256sum -- "${final##*/}" >"${final##*/}.sha256")
echo "created $final"

# Rotation: names contain a UTC timestamp, so reverse order = newest to oldest; delete the keep+1th and older
while IFS= read -r -d '' old; do
  rm -f -- "$old" "$old.sha256"
  echo "rotated $old"
done < <(find "$dest" -maxdepth 1 -type f -name "$name-*.tar.gz" -print0 | sort -z -r | tail -z -n +"$((keep + 1))")

Note trap 'rm -f -- "$tmp"' EXIT Use single quotes: variables expand only when the trap fires; on success mv , after which $tmp no longer exists,rm -f silently harmless. sort -z,tail -z is a GNU extension (on macOS, install the Homebrew coreutils version of gsort/gtail).

2. Run 4 times, keep 3 copies (actual run)

for i in 1 2 3 4; do ./backup.sh ~/bashlab/data ~/bashlab/backups 3; sleep 1.1; done
ls -1 ~/bashlab/backups
(cd ~/bashlab/backups && sha256sum -c ./*.sha256)
created ~/bashlab/backups/data-20261117T070823Z.tar.gz
created ~/bashlab/backups/data-20261117T070824Z.tar.gz
created ~/bashlab/backups/data-20261117T070825Z.tar.gz
created ~/bashlab/backups/data-20261117T070826Z.tar.gz
rotated ~/bashlab/backups/data-20261117T070823Z.tar.gz
data-20261117T070824Z.tar.gz
data-20261117T070824Z.tar.gz.sha256
data-20261117T070825Z.tar.gz
data-20261117T070825Z.tar.gz.sha256
data-20261117T070826Z.tar.gz
data-20261117T070826Z.tar.gz.sha256
data-20261117T070824Z.tar.gz: OK
data-20261117T070825Z.tar.gz: OK
data-20261117T070826Z.tar.gz: OK

3. Restore drill and corruption check (actual run)

latest=$(find ~/bashlab/backups -maxdepth 1 -name 'data-*.tar.gz' | sort | tail -1)
r=$(mktemp -d); tar -xzf "$latest" -C "$r"
diff -r ~/bashlab/data "$r/data" && echo "restore OK: identical"
tar -tzf "$latest" | head -5
echo garbage >> "$latest"                         # simulate corruption
(cd ~/bashlab/backups && sha256sum -c "${latest##*/}.sha256"); echo "rc=$?"
restore OK: identical
data/
data/files/
data/files/new\nline
data/files/my report.txt
data/files/-rf
data-20261117T070826Z.tar.gz: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
rc=1

tar -t Newlines in filenames are displayed as \n; the archive stores the real filename, so after restore it is diff -r identical.

4. Locking and age-based rotation (actual run)

( exec 9>~/bashlab/backups/.backup.lock; flock 9; sleep 3 ) &   # simulate a backup that is running
sleep 0.5; ./backup.sh ~/bashlab/data ~/bashlab/backups 3; echo "rc=$?"; wait
touch -d '10 days ago' ~/bashlab/backups/data-20261101T000000Z.tar.gz
find ~/bashlab/backups -maxdepth 1 -name 'data-*.tar.gz' -mtime +7 -print   # dry-run first, then switch to -delete
Another backup is already running
rc=1
~/bashlab/backups/data-20261101T000000Z.tar.gz

5. (Optional) off-site copy

# another host (zero cost: can be another directory on localhost)
rsync -a --partial ~/bashlab/backups/ backup-host:/srv/backups/$(hostname)/
ssh -n backup-host "cd /srv/backups/$(hostname) && sha256sum -c --quiet ./*.sha256"
# cloud (incurs small storage costs; not run by default in this course)
# az storage blob upload --account-name <acct> -c backups -f "$latest" -n "$(hostname)/${latest##*/}" --auth-mode login
# aws s3 cp "$latest" "s3://<bucket>/$(hostname)/" --storage-class STANDARD_IA

Lab: back up ~/bashlab/data and complete a restore drill

Setup: confirm the dataset exists (Lesson 1 make-data.sh, which includes the “weird name” file):
ls ~/bashlab/data ~/bashlab/data/files | head
mkdir -p ~/bashlab/m5 && cd ~/bashlab/m5
Save the script: copy the script from the “Commands” page backup.sh and save it as ~/bashlab/m5/backup.sh and chmod +x; first bash -n backup.sh do a syntax check.
Run and rotate: run 4 times (keep=3), confirm only 3 copies remain and the checksums pass (see the output in paragraph 2 of the “Commands” page).
Fault injection 1: disk full / tar failure— make an unreadable file appear in the source directory and check whether a failed run leaves behind .part:
install -m 000 /dev/null ~/bashlab/data/secret.bin     # unreadable to normal users (no effect as root)
./backup.sh ~/bashlab/data ~/bashlab/backups 3; echo "rc=$?"
ls -A ~/bashlab/backups | grep part || echo "No leftover .part ✓"
rm -f ~/bashlab/data/secret.bin
tar: data/secret.bin: Cannot open: Permission denied
tar: Exiting with failure status due to previous errors
rc=2
No leftover .part ✓

GNU tar exits with status 2 (fatal error) when it hits an unreadable file; set -e this makes the script exit immediately, the EXIT trap deletes the temp file, rotation does not run, and the old backups stay intact.

Fault injection 2: concurrency: in one terminal, run flock ~/bashlab/backups/.backup.lock sleep 30, then run a backup in a second terminal and confirm you get “Another backup is already running” and rc=1.
Restore drill: following paragraph 3 of the “Commands” page, extract the latest backup to a temp directory and diff -r; add the drill commands to ~/bashlab/m5/restore-drill.sh, as part of a scheduled job (Module 6).
Cleanup: rm -rf ~/bashlab/backups/.backup.lock (The lock file can stay; it does not affect the next run). The backup files are kept for Module 6.

Case 1: age-based rotation deleted all backups

Problem: The backup job failed 10 days in a row due to expired credentials, with no alert; the find /backups -mtime +7 -delete ran as usual every day, and from day 8 onward it gradually deleted all backups. Fix:① Run rotation only after “this backup succeeds”, within the same script; ② switch to keeping a fixed number of copies; ③ monitor the “age of the latest backup” (alert if older than 26 hours) rather than only whether the job failed. Limitation: Keep-by-count needs N adjusted whenever the schedule changes.

Case 2: backup “succeeded” but restore failed

Problem: The tar archive used absolute paths and was extracted with BSD tar on macOS, so permissions and extended attributes were lost. In another incident, a backup file was truncated by a sync tool and never verified. Fix: Archive with relative paths; run an automated restore drill every week (extract to a temp directory + spot-check checksums + application-level checks, such as pg_restore --list); every copy ships with .sha256. Limitation: Restore drills consume I/O, so run them during off-peak hours.

Case 3: database directory tarred directly

Problem: The PostgreSQL data directory was tarred directly while the database was running; after restore, the database would not start (inconsistent files). Fix: Use pg_dump / pg_basebackup or a filesystem / cloud disk snapshot (freeze I/O first); the backup script only handles “call a consistency tool, archive, verify and rotate”. Limitation: Large databases should use incremental / PITR approaches, which are beyond the scope of shell scripts.

Common errors and fixes

tar: Removing leading `/' from member names

Cause: Archived with absolute paths; GNU tar automatically strips the leading / (this is a safety measure, not an error).

Fix:tar -C /parent -czf out.tar.gz -- dirname, so the archive contains clean relative paths.

tar: file changed as we read it (exit code 1)

Cause: The file was modified during archiving (logs, database files). GNU tar returns 1 for this (“some files differ”), so with set -e , the script exits.

tar … ; echo "tar rc=$?"   # 0 success · 1 a file changed while being read · 2 fatal error

Fix: Snapshot or export volatile data first; if acceptable for the business, explicitly allow 1: tar … || [[ $? -eq 1 ]], and log a warning.

sha256sum: WARNING: 1 computed checksum did NOT match

Cause: The file was corrupted or truncated during copy / storage, or the checksum file refers to a different version.

Fix: Restore from another copy; check the transfer tool (use rsync --checksum or the object store's MD5/CRC checks); alert instead of silently skipping.

mktemp: failed to create file via template … : Permission denied / No space left on device

Cause: The destination directory is not writable or is full.

df -h "$dest"; df -i "$dest"; ls -ld "$dest"

Fix: Check free space before backing up (for example, compare avail=$(df --output=avail -k "$dest" | tail -1) with the source size du -sk ). Rotate-then-backup should only be considered when there is a real space problem and at least 2 copies are kept.

Command-line exercise
1. In /backups , keep only the newest 5 app-*.tar.gz (file names may contain spaces), and delete the rest along with their .sha256 files.
find /backups -maxdepth 1 -type f -name 'app-*.tar.gz' -print0 | sort -z -r | tail -z -n +6 |
while IFS= read -r -d '' f; do rm -f -- "$f" "$f.sha256"; done
2. Write a one-line check: exit 1 if the latest backup is older than 26 hours (usable for monitoring).
[[ -n $(find /backups -maxdepth 1 -name 'app-*.tar.gz' -mmin -$((26*60)) -print -quit) ]] || { echo "Latest backup is too old" >&2; exit 1; }
Scenario analysis
The backup target is an NFS mount point. One day NFS was not mounted, so the script wrote backups into a local empty directory with the same name until the root partition filled up. How do you prevent this?

① Check the mount before writing: mountpoint -q /mnt/backup || { echo "Not mounted"; exit 1; }; ② or place a sentinel file on the mount point (.backup-target), write only when it exists; ③ for a systemd timer, use RequiresMountsFor=/mnt/backup (Module 6); ④ local partition monitoring and quotas; ⑤ alert on backup failures (non-zero exit code + OnFailure).

Verified instructional videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 17 - Backup Script) — Learn Linux TV
English · Bash series, episode 17: writing backup scripts (compare with the atomic writes and rotation in this module)

Official documentation

Video storyboard script (about 80 seconds)

This lesson cannot directly generate a video/MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: the progress bar is halfway when “disk full” appears, leaving a backup file with a normal name but only half its contents.
Narration: writing directly to the final filename leaves a corrupt backup that looks normal when the write fails.
Shot 2 · 20–45s
Visual: the file is written with a .part suffix; after the checksum passes it is “renamed” to the final name, and a .sha256 file is generated next to it.
Narration: write to a temp file first, verify it, atomically rename it, then generate the checksum.
Shot 3 · 45–65s
Visual: a calendar grid; with the age-based policy the cells turn grey day by day after backups stop, until all are empty; with the count-based policy, 7 green cells are always kept.
Narration: count-based rotation is safer, because even if backups stop it will not delete all the old ones.
Shot 4 · 65–80s
Visual: extract to a temp directory; diff shows identical, with a green checkmark.
Narration: finally, run restore drills regularly. A backup that has never been restored is not a backup.
or score ≥ 70% on the “Quiz”

Module 6 · Scheduled execution: cron and systemd timers

35:00 – 42:00 · The same backup script with two schedulers: differences in environment, missed jobs, overlapping runs, logs and alerts
7 mincron · systemd 255+ (259 on Ubuntu 26.04)★★★★☆
Learning objectives
  • Read and write crontab (5 time fields,% escaping,MAILTO,CRON_TZ), explain three pitfalls of the cron environment: a minimal PATH,/bin/sh, and no terminal.
  • For the script, write .service (Type=oneshot) + .timer (OnCalendar,Persistent,RandomizedDelaySec) use systemd-analyze calendar to validate the expression.
  • Compare how the two behave for “missed jobs”, “overlapping runs”, “logs”, “failure notifications” and “dependencies (mounts, network)”, then make a choice.
  • Use user-level timers (systemctl --user + loginctl enable-linger) to schedule opsctl without requiring root.
Prerequisites:Linux course, Lesson 2(systemd units, journald). Importance:★★★★☆

What: two schedulers

cron (on Debian/Ubuntu it is a derivative of Vixie cron cron, on RHEL-family systems it is cronie): the daemon checks the crontab every minute and runs due jobs through /bin/sh -c , executing command lines; output is sent by local mail to MAILTO (lost if there is no MTA). systemd timer: .timer The timer unit, when its time comes,starts the same-named (or Unit= specified) .service unit; the service runs in a clean environment managed by systemd, with output going to journald.

Why: typical causes of scheduled-job problems

  • “works by hand, fails in cron”: cron's PATH usually contains only /usr/bin:/bin, so it cannot find /usr/local/bin/opsctl,~/.local/bin/az; it does not load ~/.bashrc; it uses sh rather than Bash.
  • “%” gets swallowed: an unescaped % means a newline,date +%F so it must be written as date +\%F.
  • Missed jobs: if the machine is off at 02:00 (laptops, on-demand VMs), cron does not catch up; systemd's Persistent=true runs the missed job once after boot.
  • Overlapping runs: if the previous run is still going, cron starts a new run anyway; in systemd, if the service is still in the active (activating) state, the timer firing again does not start a second instance.
  • Silent failures: nobody reads cron's output; systemd can OnFailure= trigger a notification unit, and failures are visible in systemctl --failed .

How: key syntax

# crontab: min hour day month weekday  command
# ┌──────── minute (0-59)
# │ ┌────── hour (0-23)
# │ │ ┌──── day of month (1-31)
# │ │ │ ┌── month (1-12)
# │ │ │ │ ┌ day of week (0-7, 0 and 7 are Sunday)
  0 2 * * *   /home/lab/bashlab/opsctl/bin/opsctl backup /home/lab/bashlab/data
  */5 * * * * flock -n /tmp/health.lock opsctl health http://127.0.0.1:8080/healthz

# systemd OnCalendar: weekday year-month-day hour:minute:second
  OnCalendar=*-*-* 02:00:00        # every day at 02:00 (daily means 00:00)
  OnCalendar=Mon..Fri *-*-* 09:30  # weekdays 09:30
  OnCalendar=*:0/5                 # every 5 minutes
  OnCalendar=*-*-01 03:00          # 1st of every month at 03:00
Dimensioncronsystemd timer
ConfigurationOne crontab line.service + .timer Two files
Shell / environment/bin/sh, minimal PATH, variables can be set at the top of the crontabNo shell (ExecStart is exec'd directly) Environment= / EnvironmentFile=
Missed jobsNot run (needs anacron)Persistent=true Run after boot
Overlapping runsMay overlap; needs flock -n; a running service is not started again
Random jitterDIY sleep $((RANDOM % 600))RandomizedDelaySec=
LogsMail / redirect yourselfjournald: journalctl -u x.service
Failure notificationsRelies on mailOnFailure=,systemctl --failed
Dependencies & resourcesNoneRequiresMountsFor=,After=network-online.target,CPUQuota=,TimeoutStartSec=, sandboxing options
PortabilityAlmost all Unix systems, container imagesOnly on systemd systems; usually unavailable in containers
Validation(no built-in)systemd-analyze calendar,systemd-analyze verify,systemctl list-timers

When: how to choose

  • On systemd hosts, for new jobs: prefer systemd timers (better logs, catch-up, overlap prevention, and dependencies).
  • Non-systemd environments (containers, BSD, macOS using launchd), or teams that already have many crontab conventions: cron + the “robust cron line” from this module.
  • Cross-host scheduling or anything needing approvals and history: scheduled CI pipelines (GitHub Actions schedule:, GitLab scheduled pipelines, see Module 7) or a job scheduling platform.
Common misconceptions① “OnCalendar=daily is 2 am”—it is actually 00:00 (verified systemd-analyze calendar daily normalized to *-*-* 00:00:00). ② “Enabling the .service makes it run on a schedule”—what needs to be enabled is enable --now the .timer; .service usually has no [Install]. ③ “User timers keep running after I log out”—by default the user instance stops when the last session ends, so you need loginctl enable-linger user. ④ “Just set source ~/.bashrc and it works”—many .bashrc at the top returns right away in a non-interactive shell; set it explicitly in the script or in the crontab PATH.

Architecture diagram: two scheduling paths

cron daemonChecks crontab every minute /bin/sh -c "command line"PATH=/usr/bin:/bin · no TTY opsctl backup …may overlap with the previous run output → mailed via MAILTOlost without an MTA opsctl-backup.timerOnCalendar · PersistentRandomizedDelaySec start opsctl-backup.serviceType=oneshot · clean environmentalready running → not started again ExecStart=…/opsctlexec directly, no shellexit code → Result= journald + OnFailure=journalctl --user -u …failure triggers notification unit
Figure 6-1: cron forks a shell directly; a systemd timer just “starts a service unit at a certain time”

Timeline diagram: missed jobs and overlaps

crontimer 01:00–03:00 powered off 02:00 missed, not re-run 03:00 run after boot (Persistent) previous run still going, cron starts another (overlap) service still active when triggered → no second instance
Figure 6-2: missed runs during downtime and overlapping long jobs: how the two schedulers behave differently

Comparison animation: how cron and the timer behave over the same day

Job: back up every day at 02:00 (may take a long time). Pick a scenario and step through the events on both timelines and the matching real logs.

Ready.
$ systemctl --user list-timers

Command cheat sheet

CommandPurposeKey points
crontab -e / -lEdit / view the current user's crontabChecks syntax on save
grep CRON /var/log/syslog / journalctl -u cronView cron execution logOnly records that it ran, not its output
systemd-analyze calendar 'expr'Validate an OnCalendar expression--iterations=N Shows the next several run times
systemd-analyze verify x.timerStatically check unit filesWarns about misspelled keys
systemctl --user enable --now x.timerEnable a user timerEnable the .timer
systemctl --user list-timersNext / last trigger timesSystem-level: drop --user
systemctl --user start x.serviceRun once immediatelymost useful for testing
journalctl --user -u x.service -n 50View output-f Follow
loginctl enable-linger $USERKeep the user instance running when the user is logged outRequires root or polkit permission
systemd-run --user --on-calendar=… cmdTransient timer (no file written)good for one-off experiments

1. Robust crontab entry

crontab -e
# ---- crontab content below ----
SHELL=/bin/bash
PATH=/home/lab/bashlab/opsctl/bin:/usr/local/bin:/usr/bin:/bin
MAILTO=""
CRON_TZ=UTC
# back up daily at 02:00 UTC; prevent overlap; random delay of 0–599 seconds; append output to the log with timestamps
0 2 * * * flock -n /tmp/opsctl-backup.lock bash -c 'sleep $((RANDOM \% 600)); opsctl backup -k 14 "$HOME/bashlab/data"' >> "$HOME/bashlab/logs/backup.log" 2>&1
# health check every 5 minutes; on failure, write to the system log with logger
*/5 * * * * opsctl health -r 3 http://127.0.0.1:8080/healthz 2>&1 | logger -t opsctl-health

Key points: % Write it as \%; MAILTO="" turn off mail (output is already redirected); CRON_TZ supported by cronie and Debian cron (see man 5 crontab for details); SHELL=/bin/bash let the command line be parsed by Bash. ~/bashlab/logs needs to be created first. Note the second line: after the pipe, cron only sees logger's exit code.

2. User-level systemd service + timer

mkdir -p ~/.config/systemd/user ~/bashlab/logs
cat > ~/.config/systemd/user/opsctl-backup.service <<'EOF'
[Unit]
Description=opsctl backup of ~/bashlab/data
# when the backup target is on a mount point: RequiresMountsFor=/mnt/backup
OnFailure=opsctl-notify@%n.service

[Service]
Type=oneshot
Environment=OPSCTL_BACKUP_KEEP=14 NO_COLOR=1
ExecStart=%h/bashlab/opsctl/bin/opsctl backup -o %h/bashlab/backups %h/bashlab/data
TimeoutStartSec=30min
Nice=10
IOSchedulingClass=idle
EOF

cat > ~/.config/systemd/user/opsctl-backup.timer <<'EOF'
[Unit]
Description=Daily opsctl backup

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
RandomizedDelaySec=10min

[Install]
WantedBy=timers.target
EOF

cat > ~/.config/systemd/user/opsctl-notify@.service <<'EOF'
[Unit]
Description=Notify failure of %i

[Service]
Type=oneshot
ExecStart=/usr/bin/logger -p user.err -t opsctl-notify "unit %i failed"
EOF

systemd-analyze --user verify ~/.config/systemd/user/opsctl-backup.*
systemctl --user daemon-reload
systemctl --user enable --now opsctl-backup.timer
systemctl --user list-timers opsctl-backup.timer
NEXT                         LEFT      LAST PASSED UNIT                 ACTIVATES
Wed 2026-11-18 02:04:17 UTC  19h left  -    -      opsctl-backup.timer  opsctl-backup.service

1 timers listed.

%h is the user home directory specifier,%n is the full unit name,%i is the template instance name (systemd.unit(5)). In production, you can replace opsctl-notify@ with a script that calls a webhook. NEXT The time includes the random delay.

3. Validate calendar expressions (actual run)

systemd-analyze calendar --iterations=3 '*-*-* 02:00:00'
systemd-analyze calendar daily
Normalized form: *-*-* 02:00:00
    Next elapse: Wed 2026-11-18 02:00:00 EST
       (in UTC): Wed 2026-11-18 07:00:00 UTC
       From now: 23h left
   Iteration #2: Thu 2026-11-19 02:00:00 EST
       (in UTC): Thu 2026-11-19 07:00:00 UTC
       From now: 1 day 23h left
   Iteration #3: Fri 2026-11-20 02:00:00 EST
       (in UTC): Fri 2026-11-20 07:00:00 UTC
       From now: 2 days left
  Original form: daily
Normalized form: *-*-* 00:00:00
…

OnCalendar uses the system local timezone by default; to fix a timezone, append the timezone name to the expression, for example *-*-* 02:00:00 UTC.

4. Trigger manually and view logs

systemctl --user start opsctl-backup.service      # run once now (waits in the foreground for the oneshot to finish)
systemctl --user status opsctl-backup.service --no-pager
journalctl --user -u opsctl-backup.service -n 20 --no-pager
loginctl show-user "$USER" -p Linger              # only Linger=yes keeps it running after logout

Lab: run the backup every 2 minutes with a user-level timer (switch back to daily after the demo)

Requires systemd (linuxlab VM; on WSL2, in /etc/wsl.conf the [boot] section, set systemd=true and wsl --shutdown restart). In containers systemd is usually missing, so you can do only the cron part. The opsctl v0.3's backup subcommand is completed in Module 8; finish Module 8 first and come back, or temporarily replace ExecStart with the Module 5's backup.sh.

Create the unit files: following paragraph 2 of the “Commands” page, create the three files.
Change it to every 2 minutes (for the experiment only) and enable:
mkdir -p ~/.config/systemd/user/opsctl-backup.timer.d
printf '[Timer]\nOnCalendar=\nOnCalendar=*:0/2\nRandomizedDelaySec=0\n' \
  > ~/.config/systemd/user/opsctl-backup.timer.d/lab.conf
systemctl --user daemon-reload
systemctl --user enable --now opsctl-backup.timer
systemctl --user list-timers opsctl-backup.timer --no-pager

In the drop-in, first write an empty OnCalendar= to clear the original value, then set the new value (the reset rule for list-type settings).

Observe: wait 2–4 minutes:
journalctl --user -u opsctl-backup.service --since -10min --no-pager | tail
ls -1t ~/bashlab/backups | head -4
Nov 17 10:02:00 linuxlab systemd[1234]: Starting opsctl-backup.service - opsctl backup of ~/bashlab/data...
Nov 17 10:02:00 linuxlab opsctl[5678]: 2026-11-17T10:02:00+0000 INFO  opsctl[5678]: backup created: /home/lab/bashlab/backups/data-20261117T100200Z.tar.gz (4.0K)
Nov 17 10:02:00 linuxlab systemd[1234]: Finished opsctl-backup.service - opsctl backup of ~/bashlab/data.
Fault injection: temporarily make the source directory missing, to trigger the failure and OnFailure:
mv ~/bashlab/data ~/bashlab/data.off
systemctl --user start opsctl-backup.service; echo "rc=$?"
systemctl --user --failed --no-pager
journalctl --user -t opsctl-notify -n 3 --no-pager; journalctl -t opsctl-notify -n 3 --no-pager
mv ~/bashlab/data.off ~/bashlab/data; systemctl --user reset-failed

opsctl returns usage error 2 for “not a directory”; the service enters the failed state, and OnFailure starts the notification unit (logs written by logger may be in the user or system journal, depending on configuration).

(Optional) cron comparison: crontab -e Add */2 * * * * env > /tmp/cron-env.txt, and two minutes later cat /tmp/cron-env.txt, compare with the interactive shell's env: how short is PATH?
Cleanup:
rm ~/.config/systemd/user/opsctl-backup.timer.d/lab.conf
systemctl --user daemon-reload                       # restore to daily at 02:00; if not needed:
# systemctl --user disable --now opsctl-backup.timer
crontab -l | grep -v cron-env | crontab -            # delete the comparison cron line

Case 1: after moving to on-demand VMs, the nightly job never ran again

Problem: To save costs, the dev VMs were powered off at 20:00 and on at 08:00 every night, so the 02:00 cleanup job in cron never ran again. Fix: Switch to a systemd timer + Persistent=true: after boot, if the last trigger was earlier than the scheduled time, it runs once immediately (the timestamp is recorded in /var/lib/systemd/timers/, and user-level units keep it in ~/.local/share/systemd/timers/). Limitation: It catches up only once; it does not replay all missed runs.

Case 2: top-of-the-hour “thundering herd”

Problem: Cron on thousands of hosts all run at 0 * * * * to report metrics; the monitoring backend's CPU maxes out every hour on the hour. Fix: systemd RandomizedDelaySec=15min (random each time) or FixedRandomDelay=true (a fixed random offset per host, more predictable); in cron, compute a fixed offset minute from a hash of the hostname. Limitation: Results arrive more spread out, so alert rules need to account for the delay.

Case 3: a cron job running as root broke file permissions

Problem: Backups were written to /etc/crontab and ran as root, so the generated files were owned by root; later a normal user's cleanup script could not delete them and the disk filled up. Fix: Use a user-level timer, or set User=,Group= in a system-level unit; only elevate privileges when truly needed; systemd units can add ProtectSystem=strict,ReadWritePaths= to limit the writable scope. Limitation: Sandbox options need to be tested one by one, to avoid scripts failing on a read-only filesystem.

Common errors and fixes

/bin/sh: 1: opsctl: not found (only appears in cron)

Cause: cron's PATH does not include the directory where opsctl lives.

* * * * * env > /tmp/cron-env.txt     # temporarily add this to see cron's real environment

Fix: Set PATH=… at the top of the crontab, or use an absolute path; the script itself should not depend on the caller's PATH either.

/bin/sh: 1: Syntax error: end of file unexpected / command truncated at %

Cause: An unescaped % in crontab is converted to a newline, and everything after it becomes the command's stdin.

Fix:date +\%F; or put complex commands in a script file, so crontab only calls the script.

systemctl --user: Failed to connect to bus: No medium found (or $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined)

Cause: Switching users via su / sudo -u does not create a login session, so the user's systemd instance and D-Bus are unavailable.

loginctl show-user "$USER" -p Linger -p State; echo "$XDG_RUNTIME_DIR"

Fix: Use ssh user@host or machinectl shell user@ log in as that user; or sudo -u user XDG_RUNTIME_DIR=/run/user/$(id -u user) systemctl --user …; and loginctl enable-linger.

Timer shows n/a and never fires

Cause: Only the .service was enabled; or the .timer was changed without daemon-reload; or the OnCalendar expression is invalid.

systemctl --user list-timers --all; systemd-analyze calendar 'your expression'; systemctl --user cat opsctl-backup.timer

Fix:systemctl --user daemon-reload && systemctl --user enable --now x.timer.

Service stays in activating, and all later timer triggers are skipped

Cause: The previous run hung (for example waiting on the network, a lock, or interactive input), and systemd does not start a second instance.

Fix: Set TimeoutStartSec= (oneshot waits indefinitely by default), give network calls in the script a timeout (Module 1), and check systemctl --user status 's process tree.

Command-line exercise
1. Write one crontab line that runs /opt/bin/report.sh on weekdays at 18:30, appending output to /var/log/report.log, with the date in the log file name (YYYY-MM-DD).
30 18 * * 1-5 /opt/bin/report.sh >> /var/log/report-$(date +\%F).log 2>&1
2. Write the [Timer] section that runs every Sunday at 03:15 UTC, runs missed jobs after boot, and has a random delay of up to 5 minutes, and give the verification command.
[Timer]
OnCalendar=Sun *-*-* 03:15:00 UTC
Persistent=true
RandomizedDelaySec=5min
# verify: systemd-analyze calendar 'Sun *-*-* 03:15:00 UTC'
Scenario analysis
The team wants to move 40 crontab entries to systemd timers. Which behavioral differences need to be assessed in advance?

① Environment: ExecStart does not go through a shell, so pipes / redirects / % need to be rewritten (using /bin/bash -c or wrap it in a script), and set environment variables with Environment=; ② time zones and expression semantics (in cron, the day-of-month and day-of-week fields are OR-ed, while OnCalendar uses AND); ③ changes in overlap behavior (jobs that relied on running in parallel); ④ whether catch-up of missed runs (Persistent) is expected; ⑤ output moves from mail to journald, and alerts become OnFailure; ⑥ permissions and sandboxing (User=); ⑦ use systemd-analyze calendar to check next trigger times one by one; during migration, do not enable both sides at the same time.

Verified instructional videos

▶
Automate Your Tasks with systemd Timers: A Step-by-Step Guide — Learn Linux TV
English · step-by-step systemd timer tutorial
▶
Linux Crash Course - Scheduling Tasks with Cron — Learn Linux TV
English · crontab syntax and usage
▶
Cron Jobs For Beginners | Linux Task Scheduling — Akamai Developers
English · cron basics

Official documentation

Video storyboard script (about 80 seconds)

This lesson cannot directly generate a video/MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: the script runs successfully by hand in the terminal; switch to the cron log showing “opsctl: not found”.
Narration: it works by hand but not in cron, usually because cron's PATH is very short.
Shot 2 · 20–45s
Visual: two timelines; in the grey powered-off period, cron's job marker turns red, and the timer runs the job after boot.
Narration: the Persistent option of a systemd timer runs missed jobs after boot.
Shot 3 · 45–65s
Visual: long job bars; cron stacks a second red bar, while the timer has only one.
Narration: if the previous run has not finished, cron starts another run; systemd does not start the same service twice.
Shot 4 · 65–80s
Visual: journalctl -u shows output; on failure, OnFailure sends a notification.
Narration: logs go to journald, failures can trigger a notification unit, and silent failures become visible.
or score ≥ 70% on the “Quiz”

Module 7 · Running scripts in CI: GitHub Actions / GitLab CI

42:00 – 50:00 · The same opsctl, run reliably on a runner: shell options, exit codes, secrets, concurrency, artifacts and OIDC
8 minactions/checkout v7 · azure/login v3 · configure-aws-credentials v6★★★★☆
Learning objectives
  • Explain the difference in GitHub Actions between run: no shell specified and shell: bash (bash -e {0} vs bash --noprofile --norc -eo pipefail {0}), and the GitLab rule that “when multiple commands are merged into one line, only the last one is reported”.
  • Put the logic in a script in the repo (opsctl); the CI YAML only handles “prepare the environment + call the script + collect results”.
  • Handle secrets correctly (automatic masking,::add-mask::, masked variables), concurrency (concurrency / resource_group), artifacts and digests ($GITHUB_STEP_SUMMARY,artifacts:).
  • Understand how to use OIDC so CI can call az / aws with short-lived credentials (no long-term keys stored); details are in the GitHub / GitLab courses.
Prerequisites: Modules 1–6 of this course. For CI platform details, see GitHub (8 hours) and GitLab (8 hours). Importance:★★★★☆

What: how CI runs your Bash

GitHub Actions: each run: step's content is written to a temporary script file, and executed using the template of shell: 's template. In the official docs (Workflow syntax), the templates are: unspecified shell (non-Windows) → bash -e {0}; shell: bash → bash --noprofile --norc -eo pipefail {0}; shell: sh → sh -e {0}. In other words,only when you explicitly write shell: bash is pipefail enabled.. GitLab CI: the Runner runs each item in the script: array in order; any non-zero return fails the job and later commands do not run; if you write several commands as one string (for example, using > folding), only the last result is reported (GitLab docs “Scripts and job logs”).

Why: how scripts differ in CI from local

  • No TTY: interactive prompts (ssh host confirmation,read, pagers) hang or fail immediately.
  • A clean, short-lived environment: every run uses a new runner / container; local ~/.bashrc, logged-in az / aws sessions, and installed tools are all absent.
  • Logs are visible to people with permission: set -x can print tokens from the command line (the platform masks registered secrets on a best-effort basis, but concatenated or encoded values are not recognized).
  • Concurrency: multiple branches / pushes can run at the same time, so deploy jobs must be serialized.

How: conventions for reliable CI scripts

  1. Put business logic in repo scripts (bin/opsctl,ci/smoke.sh), and the script itself includes set -Eeuo pipefail so it does not depend on CI's default shell options, and local and CI behave the same.
  2. In the YAML, explicitly set shell: bash (GitHub), or use an image that includes Bash (GitLab image: bash:5.3 needs apk add as a dependency).
  3. Express results with exit codes: 0 for success, non-zero for failure; when you need to “allow failure”, use the platform mechanism (continue-on-error / allow_failure), rather than swallowing errors in the script.
  4. Output machine-readable results (JUnit / JSON / Markdown summary) and upload them as artifacts.
  5. Exchange cloud credentials for short-lived tokens using OIDC; add concurrency locks and environment approvals to deploy jobs.
RequirementGitHub ActionsGitLab CI
Default shell optionsUnspecified: bash -e; shell: bash: -eo pipefaileach script item stops on failure
Scheduled runson: schedule: - cron: '0 2 * * *' (UTC)Pipeline schedules in project settings + rules: if: $CI_PIPELINE_SOURCE == "schedule"
Manual runsworkflow_dispatchwhen: manual / Run pipeline
Secrets${{ secrets.X }} (automatic masking),echo "::add-mask::$v"Masked / Protected variables
Deploy serializationconcurrency: { group: deploy-prod, cancel-in-progress: false }resource_group: production
Results$GITHUB_STEP_SUMMARY,actions/upload-artifact@v7,::error::artifacts: paths / reports: junit
Cloud login (OIDC)permissions: id-token: write + azure/login@v3 / aws-actions/configure-aws-credentials@v6id_tokens: + az login --federated-token / aws sts assume-role-with-web-identity

When: put it in CI or in a host timer?

Tasks that need code review, approvals, a traceable history, or centralized credential management (deployments, inspection reports, cloud resource cleanup) belong in CI. Tasks that need access to internal network or local resources, run at high frequency (minutes), or must run even when CI is unavailable (local backups, health checks) belong in a host timer (Module 6).

Common misconceptions① “GitHub's run has pipefail by default”—false; pipefail is only on when you explicitly write shell: bash . ② “set -x Running it in CI is fine, since secrets are masked”—masking is string replacement of known values; base64 / URL-encoded values, or an Authorization header built by concatenation, are not recognized. ③ “Just rerun it when CI fails”—deploy jobs must be idempotent or reversible (Module 4), otherwise reruns can stack side effects. ④ “schedule uses my local timezone”—GitHub Actions cron runs in UTC (see the official docs), and it may be delayed under heavy load.

Architecture diagram: the script inside one CI job

Triggerpush · schedule · manual RunnerFresh VM / container checkout + dependenciesapt / apk install curl jq run: stepbash --noprofile --norc-eo pipefail temp script Resultexit code → ✓/✗ Script in the repo (the real logic)bin/opsctl health/backup/deployincludes set -Eeuo pipefail, reproducible locally Secrets & credentialssecrets / masked variables (masking)OIDC → short-lived cloud tokens (no long-term keys stored) Artifacts & summary$GITHUB_STEP_SUMMARY (Markdown)upload-artifact / artifacts: paths
Figure 7-1: YAML only orchestrates; the logic lives in repo scripts; exit codes decide job success or failure

Data flow diagram: what happens when a step fails

Step 1: lint ✓ Step 2: opsctl healthexit 1 → step fails Step 3: deploy (skipped) if: always() / when: alwaysUpload logs and summary Failure inside a pipe: curl … | jq … —— without pipefail, curl's failure is hidden by jq's 0, so the step shows ✓ GitHub: explicit shell: bash; GitLab: set -o pipefail inside the script file; safest: put the logic in a script that sets strict mode itself
Figure 7-2: how failure propagates: step → job → pipeline; cleanup steps must explicitly declare “always run”

Animation: CI job execution flow (including one failure)

Choose a platform and a scenario, then step through how the runner executes your script and how the exit code determines the state of the step and the job.

Ready.
Runner: waiting for job…

Key points cheat sheet

SyntaxPlatformPurpose
defaults: run: shell: bashGitHubUse -eo pipefail
echo "name=value" >> "$GITHUB_OUTPUT"GitHubfor step outputs (steps.id.outputs.name)
echo "### Result" >> "$GITHUB_STEP_SUMMARY"GitHubjob summary (Markdown)
echo "::error file=x.sh,line=3::message"GitHubannotation (shown in the PR)
echo "::add-mask::$value"GitHubalso mask sensitive values generated at runtime
if: always() / if: failure()GitHubCleanup / failure notification step
resource_group: productionGitLabjobs in the same resource group run serially
artifacts: when: alwaysGitLabkeep logs even on failure
CI=trueBothscripts can use this to disable color / interaction

1. GitHub Actions: .github/workflows/opsctl.yml

name: opsctl
on:
  push:
    paths: ['opsctl/**', '.github/workflows/opsctl.yml']
  schedule:
    - cron: '17 2 * * *'          # every day at 02:17 UTC (avoids the top-of-the-hour peak)
  workflow_dispatch:

permissions:
  contents: read

defaults:
  run:
    shell: bash                    # → bash --noprofile --norc -eo pipefail {0}

jobs:
  smoke:
    runs-on: ubuntu-24.04
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v7
      - name: Tools
        run: |
          bash --version | head -1
          curl --version | head -1
          command -v shellcheck && shellcheck --version | sed -n 2p || echo "shellcheck not preinstalled"
      - name: Lint
        run: shellcheck -x opsctl/bin/opsctl opsctl/lib/*.sh
      - name: Start mock API
        run: |
          python3 opsctl/test/mockapi.py 8000 2>mock.log &
          for i in {1..20}; do curl -fsS http://127.0.0.1:8000/healthz >/dev/null && break; sleep 0.5; done
      - name: Smoke test opsctl
        run: |
          export PATH="$PWD/opsctl/bin:$PATH"
          opsctl version
          opsctl health -r 4 "http://127.0.0.1:8000/flaky?fail=2&key=ci-$GITHUB_RUN_ID"
          mkdir -p data && echo hello > data/a.txt
          opsctl backup -o "$RUNNER_TEMP/backups" -k 2 data
          {
            echo "### opsctl smoke ✅"
            echo '| Check | Result |'
            echo '|---|---|'
            echo "| health | OK |"
            echo "| backup | $(ls "$RUNNER_TEMP/backups" | grep -c 'tar.gz$') copies |"
          } >> "$GITHUB_STEP_SUMMARY"
      - name: Upload logs
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: opsctl-logs
          path: mock.log

Key points: runs-on Pin the version (ubuntu-24.04) to avoid ubuntu-latest tool version changes caused by migration; GitHub-hosted Ubuntu runner images usually preinstall shellcheck and jq (see the software list in actions/runner-images). "$RUNNER_TEMP" is the temp directory for each job. { …; } >> file A single redirect writes a multi-line summary.

2. Optional: read-only cloud access via OIDC (no long-term keys stored)

  cloud-inventory:
    runs-on: ubuntu-24.04
    permissions:
      id-token: write              # allows requesting an OIDC token
      contents: read
    steps:
      - uses: azure/login@v3
        with:
          client-id: ${{ vars.AZURE_CLIENT_ID }}
          tenant-id: ${{ vars.AZURE_TENANT_ID }}
          subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
      - name: Inventory (read-only)
        shell: bash
        run: |
          az group list --query "[].[name, location]" -o tsv | tee rg.tsv
          echo "Resource group count: $(wc -l < rg.tsv)" >> "$GITHUB_STEP_SUMMARY"
      # AWS equivalent: aws-actions/configure-aws-credentials@v6 (role-to-assume, aws-region)

For the steps to create the federated credential / IAM OIDC provider, see GitHub course(the Actions and OIDC section). Grant the role only Reader / read-only policies.

3. GitLab CI: .gitlab-ci.yml

stages: [lint, test, deploy]

default:
  image: bash:5.3                  # official image based on Alpine
  before_script:
    - apk add --no-cache curl jq python3 coreutils util-linux tar shellcheck

lint:
  stage: lint
  script:
    - shellcheck -x opsctl/bin/opsctl opsctl/lib/*.sh

smoke:
  stage: test
  script:
    - python3 opsctl/test/mockapi.py 8000 2>mock.log &
    - for i in $(seq 20); do curl -fsS http://127.0.0.1:8000/healthz >/dev/null && break; sleep 0.5; done
    - export PATH="$CI_PROJECT_DIR/opsctl/bin:$PATH"
    - opsctl health -r 4 "http://127.0.0.1:8000/flaky?fail=2&key=ci-$CI_JOB_ID"
    - mkdir -p data && echo hello > data/a.txt
    - opsctl backup -o backups -k 2 data
  artifacts:
    when: always
    paths: [mock.log, backups/]
    expire_in: 3 days
  rules:
    - if: $CI_PIPELINE_SOURCE == "schedule"
    - changes: [opsctl/**/*]

deploy:
  stage: deploy
  resource_group: production       # only one deployment runs at a time
  script:
    - ./ci/deploy.sh               # internally calls opsctl deploy; on failure, rolls back automatically and exits 1
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: manual

Note: commands containing a colon must be quoted as a whole (GitLab docs: YAML treats key: value as a mapping); for … done Inside one script item it counts as one command. Alpine's coreutils / util-linux package provides GNU versions of mv -T,sort -z,flock (BusyBox versions have incomplete options). Package names are as listed in the Alpine repository.

4. Adapting scripts for CI

# ci/lib.sh — sourced by CI scripts
ci::group()    { [[ ${GITHUB_ACTIONS:-} == true ]] && echo "::group::$*" || echo "== $*"; }
ci::endgroup() { [[ ${GITHUB_ACTIONS:-} == true ]] && echo "::endgroup::" || true; }
ci::error()    { [[ ${GITHUB_ACTIONS:-} == true ]] && echo "::error::$*" || echo "ERROR: $*" >&2; }
ci::mask()     { [[ ${GITHUB_ACTIONS:-} == true ]] && echo "::add-mask::$1" || true; }

token=$(az account get-access-token --query accessToken -o tsv)
ci::mask "$token"            # mask first, before it can appear anywhere in logs

Lab: write a CI job for opsctl (get it running locally first)

Zero cost: Actions is free for public GitHub repositories; private repositories have a monthly free quota. Without a remote repository you can complete steps 1–3 locally only.

Put mockapi in the project, so that CI is self-contained:
cp ~/bashlab/mock/mockapi.py ~/bashlab/opsctl/test/mockapi.py
Write a CI script that runs locally ~/bashlab/opsctl/test/smoke.sh:
cat > ~/bashlab/opsctl/test/smoke.sh <<'EOF'
#!/usr/bin/env bash
# smoke test shared by local and CI
set -Eeuo pipefail
here=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
port=${SMOKE_PORT:-18000}
work=$(mktemp -d)
python3 "$here/mockapi.py" "$port" 2>"$work/mock.log" &
mock=$!
trap 'kill "$mock" 2>/dev/null || true; rm -rf "$work"' EXIT
for _ in $(seq 20); do curl -fsS "http://127.0.0.1:$port/healthz" >/dev/null 2>&1 && break; sleep 0.3; done

O="$here/../bin/opsctl"
"$O" version
"$O" health -r 4 "http://127.0.0.1:$port/flaky?fail=2&key=smoke-$$"
if "$O" health -r 2 "http://127.0.0.1:$port/status/500"; then
  echo "Expected health to fail on 500, but it succeeded" >&2; exit 1
fi
mkdir -p "$work/data" && echo hi > "$work/data/a.txt"
"$O" backup -o "$work/bk" -k 2 "$work/data"
echo "SMOKE OK"
EOF
chmod +x ~/bashlab/opsctl/test/smoke.sh
~/bashlab/opsctl/test/smoke.sh; echo "rc=$?"
mockapi listening on http://127.0.0.1:18000
opsctl 0.3.0
… WARN  opsctl[23088]: health fail: http://127.0.0.1:18000/flaky?fail=2&key=smoke-23074 code=503 curl_rc=0
… WARN  opsctl[23088]: attempt 1/4 failed (exit 1), retrying in 0.554s
… WARN  opsctl[23088]: health fail: http://127.0.0.1:18000/flaky?fail=2&key=smoke-23074 code=503 curl_rc=0
… WARN  opsctl[23088]: attempt 2/4 failed (exit 1), retrying in 1.286s
… INFO  opsctl[23088]: health ok: http://127.0.0.1:18000/flaky?fail=2&key=smoke-23074 code=200 time=0.001236s
… INFO  opsctl[23088]: attempt 3 succeeded: health::probe http://127.0.0.1:18000/flaky?fail=2&key=smoke-23074 5 200
… WARN  opsctl[23103]: health fail: http://127.0.0.1:18000/status/500 code=500 curl_rc=0
… WARN  opsctl[23103]: attempt 1/2 failed (exit 1), retrying in 0.123s
… WARN  opsctl[23103]: health fail: http://127.0.0.1:18000/status/500 code=500 curl_rc=0
… ERROR opsctl[23103]: giving up after 2 attempts (exit 1): health::probe http://127.0.0.1:18000/status/500 5 200
… INFO  opsctl[23115]: backup created: /tmp/tmp.2EhZFQnGOY/bk/data-20261117T080147Z.tar.gz (4.0K)
SMOKE OK
rc=0
Write a workflow: in the repo root, create .github/workflows/opsctl.yml, following paragraph 1 of the “Commands” page, and simplify the Smoke step to run: opsctl/test/smoke.sh. (GitLab users: script: [opsctl/test/smoke.sh].)
Statically check the YAML locally (Optional): actionlint (GitHub) or GitLab's CI Lint page; after pushing, check the results and the summary on the Actions / Pipelines page.
Fault injection: in smoke.sh, change the fail=2 to fail=9, push, confirm the job fails and the log contains health fail / giving up entry, and the artifact is still uploaded (if: always() / when: always). Revert and push again.
Cleanup: nothing local needs cleaning up; if you created a temporary repository for the lab, you can delete it on the platform.

Case 1: a pipe swallowed the failure and a bad config was published

Problem: A GitHub Actions step run: curl -s "$CONFIG_URL" | jq . > config.json (no shell specified → bash -e no pipefail). The config service returned a 500 HTML page and jq errored…, but this time curl returned an empty response,jq . with empty input, jq printed nothing and exited 0, so the step passed and the empty config was packaged and published. Fix:defaults.run.shell: bash; curl -fsS --fail-with-body; jq -e validate required fields; move the logic into a script with strict mode. Limitation: Platform defaults can change over time; a script that sets strict mode itself is the most reliable.

Case 2: logs leaked a token

Problem: While debugging, we added set -x, and the script ran curl -H "Authorization: Bearer $(get_token)", but the token fetched at runtime was not in the secret list, so it appeared verbatim in the logs of the public repository. Fix: Mask runtime-generated sensitive values immediately ::add-mask::; do not pass tokens on the command line (-H @file); when debugging, use set -x but for sensitive sections, use { set +x; } 2>/dev/null; rotate the leaked token. Limitation: Masking only works for exactly matching strings.

Case 3: two pushes deployed at the same time

Problem: Two merges in a row triggered two deploy jobs that ran interleaved on the same host (the Module 4 lock works on the host, so the second job failed outright, and developers kept retrying, mistakenly thinking it was a version problem). Fix: Serialize at the CI layer (concurrency: deploy-prod and cancel-in-progress: false; GitLab resource_group), keep the host-level flock as a second line of defense, and make lock-conflict messages clear (opsctl's util::lock deploy reports lock busy: …/var/lock/deploy.lock (another opsctl running?)). Limitation: Serialization queues jobs, so long deployments need a timeout set.

Common errors and fixes

Error: Process completed with exit code 141.

Cause:shell: bash With pipefail,cmd | head -1 in the pipeline, head exits early, so the upstream gets SIGPIPE (128+13).

Fix: Use grep -m1,awk 'NR==1{print; exit}' read all of the input, or sed -n '1p'; when truncation is really needed, explicitly tolerate it: { cmd || [[ $? -eq 141 ]]; } | head -1.

Permission denied: ./opsctl/bin/opsctl (exit code 126)

Cause: The file was committed from Windows, so it has no executable bit.

git ls-files -s opsctl/bin/opsctl      # 100644 = no executable bit

Fix:git update-index --chmod=+x opsctl/bin/opsctl and commit; or in CI, invoke it with bash opsctl/bin/opsctl . Also check CRLF (.gitattributes: *.sh text eol=lf).

mv: invalid option -- 'T' / sort: unrecognized option: z (GitLab job uses the Alpine image)

Cause: Alpine ships BusyBox tools by default, whose options differ from GNU's.

Fix:apk add --no-cache coreutils util-linux findutils; or switch to a Debian / Ubuntu image. Lesson 7 adds a multi-platform test matrix to CI.

OIDC: AADSTS70021: No matching federated identity record found / Not authorized to perform sts:AssumeRoleWithWebIdentity

Cause: The subject in the federated credential / trust policy (repo, branch, environment) does not match the actual token, or is missing permissions: id-token: write.

Fix: Check the subject format (for example, repo:org/repo:ref:refs/heads/main or …:environment:prod); see the OIDC section of the GitHub / GitLab courses.

Command-line exercise
1. In a GitHub Actions run step, write the result of opsctl health (OK / FAIL) as a step output health, and the step itself does not fail when the check fails.
if opsctl health -r 3 "$URL"; then r=OK; else r=FAIL; fi
echo "health=$r" >> "$GITHUB_OUTPUT"
2. Write a GitLab job snippet that runs only in scheduled pipelines opsctl backup, and keeps the backups/ directory for 7 days even on failure.
nightly-backup:
  script:
    - opsctl/bin/opsctl backup -o backups -k 7 data
  artifacts:
    when: always
    paths: [backups/]
    expire_in: 7 days
  rules:
    - if: $CI_PIPELINE_SOURCE == "schedule"
Scenario analysis
The same deployment script exits 1 when run locally, but in CI it “fails but shows green”. List the 4 places you would check.

① How it is invoked in the YAML: ./deploy.sh | tee log and the shell has no pipefail (GitHub, no shell specified); ② whether it is swallowed by || true,continue-on-error: true,allow_failure: true ; ③ in GitLab, multi-line commands are folded into one command and only the last one is checked (for example, when the last one is echo done); ④ inside the script, a different branch runs in CI (CI=true when it is set, skips checks, and when a tool is missing command -v x || exit 0); ⑤ a failure happens in a background process and there is no wait to collect its exit code.

Verified instructional videos

▶
GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker — TechWorld with Nana
English · GitHub Actions basics (workflow / job / step / runner)
▶
GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
English · GitLab CI introduction (stages, jobs, artifacts)

Official documentation

Video storyboard script (about 80 seconds)

This lesson cannot directly generate a video/MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: two YAML snippets side by side: one with no shell and one with shell: bash, with the expanded command shown below each.
Narration: a GitHub run step gets pipefail only when you explicitly write shell bash.
Shot 2 · 20–45s
Visual: step list; health turns red, deploy greys out, and upload logs still runs.
Narration: exit codes decide step success or failure. Cleanup steps must declare that they always run, so you can capture the failure state.
Shot 3 · 45–65s
Visual: in the log, the token is replaced with ***; a base64-encoded token appears verbatim, outlined in red.
Narration: masking only recognizes exact values. Sensitive values generated at runtime should be masked immediately with add-mask.
Shot 4 · 65–80s
Visual: two deploy jobs queue up, with a resource group lock icon, and run one after the other.
Narration: deployments must be serialized: GitHub uses concurrency, GitLab uses resource group.
or score ≥ 70% on the “Quiz”

Module 8 · opsctl v0.3: health, backup and deploy

50:00 – 60:00 · Bring this course's four scripts into the running project: one file per subcommand, unified logging, exit codes and configuration
10 minopsctl v0.3.0★★★★★
Learning objectives
  • For opsctl, add lib/cmd_health.sh,lib/cmd_backup.sh,lib/cmd_deploy.sh, with the functions being cmd::health,cmd::backup,cmd::deploy, dispatched automatically by the entry point.
  • Follow the project conventions from Lessons 3 and 4: each file has a # opsctl-summary: comment (help and discovery depend on it); util::usage_error / util::die <msg> [code] / util::require_cmd (EX_* = 0/1/2/3); reuse util::retry,util::lock,util::cleanup_add; options go through config::set_flag / config::get (flag > OPSCTL_<KEY> > config file > default).
  • Verify v0.3 with a set of smoke tests, and use the interactive troubleshooting tree to locate common problems from this lesson.
Prerequisites: Modules 1, 4 and 5 of this course (the logic itself), and opsctl v0.2.0 from Lesson 4 (Module 0, step 3). Importance:★★★★★ (Lesson 7 writes bats tests for these subcommands and releases v1.0)

What: the v0.3 structure (incremental changes on top of v0.2.0)

~/bashlab/opsctl/
├── bin/opsctl              # change 1 line: readonly OPSCTL_VERSION="0.3.0" (the rest is the v0.2 from Lesson 4)
├── lib/log.sh              # unchanged: log::debug/info/warn/error → stderr
├── lib/util.sh             # unchanged: EX_*, util::die, util::usage_error, util::require_cmd,
│                           #       util::cleanup_add, util::mktemp_dir, util::lock, util::retry
├── lib/config.sh           # changed: OPSCTL_DEFAULTS gains 8 new keys (health_* / backup_* / deploy_*)
├── lib/cmd_health.sh       # new: cmd::health   — health::probe + util::retry (Module 1)
├── lib/cmd_backup.sh       # new: cmd::backup   — util::lock + same-directory mktemp + atomic mv + rotation (Module 5)
├── lib/cmd_deploy.sh       # new: cmd::deploy   — deploy::switch / deploy::previous + health check + rollback (Module 4)
├── lib/cmd_servers.sh  cmd_config.sh  cmd_export.sh  cmd_doctor.sh   # Lessons 3 and 4, unchanged
├── etc/opsctl.conf         # key = value; parsed only by config::load_file against an allowlist, never sourced
├── var/lock/               # util::lock lock files (backup.lock, deploy.lock)
└── test/mockapi.py  test/smoke.sh   # Module 7 smoke tests

Why: merge them into opsctl instead of keeping four separate scripts

  • Consistency: one log format (time level opsctl[PID]: message), one set of exit codes (EX_OK/EX_ERR/EX_USAGE/EX_DEP = 0/1/2/3), one configuration precedence — cron, systemd and CI only need to understand one set of rules.
  • Reuse the v0.2 infrastructure: retries use util::retry, locks use util::lock, temp files are registered with util::cleanup_add ; the EXIT trap cleans them up, so subcommands no longer each write their own trap / flock.
  • Auto-discovery: the entry point needs no changes; it opsctl::list_commands reads each file's # opsctl-summary: comment to generate opsctl --help,opsctl::load_command loads them by name lib/cmd_<name>.sh.

How: the common skeleton for subcommands (same as cmd_export.sh from Lesson 4)

  1. The file's line 1 is # shellcheck shell=bash, line 2 is # opsctl-summary: … (without it, opsctl --help the command shows no description in help; the file name must be cmd_<name>.sh, and define cmd::<name>).
  2. Provide <name>::usage, and handle -h|--help——opsctl help health is the function that actually executes cmd::health --help.
  3. Hand-write while (($#)); case to parse short and long options; missing argument / unknown option → util::usage_error (exit code 2, and print the hint Try 'opsctl --help').
  4. Write option values into config::set_flag <key> <value>, then read them uniformly with config::get <key> <var> : precedence is flag > environment variable OPSCTL_<KEY> > etc/opsctl.conf > OPSCTL_DEFAULTS. New keys must be added to OPSCTL_DEFAULTS, otherwise same-named keys in the config file are ignored as “unknown key”.
  5. Dependencies util::require_cmd (when missing, missing required command(s): …, exit code 3); mutually exclusive util::lock <name>; temp paths util::cleanup_add.
  6. Business failures return 1 (let the caller decide, for example, deploy calls health and then rolls back); only usage, dependency and unrecoverable errors use util::die.
Subcommand / functionOptionsConfig keys (environment variables) and defaultsExit codes
health URL
cmd::health,health::probe,health::usage
-t/--timeout,-r/--retries,-e/--expecthealth_timeout=5 (OPSCTL_HEALTH_TIMEOUT),health_retries=4,health_expect=2000 healthy · 1 retries exhausted · 2 usage · 3 curl missing
backup SRC_DIR
cmd::backup,backup::usage
-o/--out-dir,-k/--keepbackup_dir=~/bashlab/backups (OPSCTL_BACKUP_DIR),backup_keep=70 · 1 lock busy / failed · 2 usage · 3 tar/sha256sum/flock missing
deploy
cmd::deploy,deploy::switch,deploy::previous,deploy::usage
-a/--artifact,-d/--root,-u/--url,-k/--keep,--rollbackdeploy_root=~/bashlab/deploy (OPSCTL_DEPLOY_ROOT),deploy_keep=5,deploy_health_url=empty (no check)0 · 1 health check failed and rolled back / lock busy / no version to roll back to · 2 usage

When: keep using Bash or rewrite?

opsctl currently has a few dozen lines per subcommand, and the logic is mostly “call external commands + check exit codes”, so Bash fits very well. Consider rewriting a subcommand in Python / Go when these signals appear: you need to parse complex JSON and do heavy computation; you need a concurrent HTTP client with fine-grained connection pooling; or a single file exceeds 200–300 lines and is hard to test. Lesson 7 adds a safety net to the existing code using bats + ShellCheck.

Common misconceptions① “Calling exit 1 directly in a subcommand is the simplest”—cmd::health is called by cmd::deploy , and if it internally calls exit deploy then has no time to roll back; for business failures, use return 1. ② “In deploy, calling cmd::health is enough”—the dispatcher only loads lib/cmd_deploy.sh, so you must first opsctl::load_command health (tested: not loading it reports cmd::health: command not found, and it is treated as a failed health check, triggering a rollback). ③ “Writing your own trap … EXIT temp-file cleanup”—this overrides the EXIT trap of the v0.2 entry point (util::_on_exit); use util::cleanup_add to register it. ④ “The lock file must be removed on exit”—flock The lock is released automatically when the file descriptor closes, and the lock file is kept long-term (per the Lesson 4 convention, located at var/lock/).

Architecture diagram: entry-point dispatch and subcommand dependencies

opsctl deploy …cron / systemd / CI / operator bin/opsctlset -Eeuo pipefailconfig::init (key = value)opsctl::load_command $cmd cmd::health (curl + backoff) cmd::backup (tar + rotation) cmd::deploy (switch + rollback) calls health v0.2 lib (unchanged)log::* · util::die · usage_errorutil::require_cmd → 3util::retry · util::lockutil::cleanup_addconfig::set_flag / get
Figure 8-1: the entry point only dispatches; subcommands share logging and helper functions; deploy reuses health

Flowchart: cmd::deploy decision logic

util::lock deploy --rollback? Yes switch(previous) No unpack + verify version switch(new) cmd::health OK clean up old releases failure switch(old) → return 1 Exit codes: 0 deploy succeeded · 1 health check failed and rolled back / lock conflict / no rollback version · 2 argument error (missing -a, package not found) Failed release directories are kept for troubleshooting; the cleanup step of the next successful deploy removes them per the retention count (never deletes current)
Figure 8-2: every deploy path ends with an explicit exit code

Animation: execution path of a single opsctl call

Pick a command and step through it to see how the entry point loads the library and config, how it dispatches, how the subcommand parses arguments, which external commands it calls, where the log goes, and what the final exit code is. The logs are real output from this lesson (timestamps are from a sample environment).

Ready.
$ cd ~/bashlab/opsctl

Full code (v0.3 = v0.2.0 + 3 new files + 2 modified files)

The steps below were actually run on the real v0.2.0 code produced by the combined Lesson 3 and 4 lab (code rebuilt by extracting it from the two lesson pages; Bash 5.2.21 / WSL2). All output is real.

1. Version number: 0.2.0 → 0.3.0 (and verify)

cd ~/bashlab/opsctl
grep -n '^readonly OPSCTL_VERSION=' bin/opsctl
sed -i 's/^readonly OPSCTL_VERSION="0\.2\.0"$/readonly OPSCTL_VERSION="0.3.0"/' bin/opsctl
grep -n '^readonly OPSCTL_VERSION=' bin/opsctl
30:readonly OPSCTL_VERSION="0.2.0"
30:readonly OPSCTL_VERSION="0.3.0"

The sed pattern matches the Lesson 4 version word for word (readonly plus double quotes). If the second grep still shows 0.2.0, your bin/opsctl differs from Lesson 4, so edit it by hand.

2. lib/config.sh: add the new keys to OPSCTL_DEFAULTS

keys=$(mktemp)
cat > "$keys" <<'EOF'
  [health_timeout]=5
  [health_retries]=4
  [health_expect]=200
  [backup_dir]="$HOME/bashlab/backups"
  [backup_keep]=7
  [deploy_root]="$HOME/bashlab/deploy"
  [deploy_keep]=5
  [deploy_health_url]=""
EOF
sed -i "/^  \[output\]=table\$/r $keys" lib/config.sh; rm -f "$keys"
sed -n '/^declare -gA OPSCTL_DEFAULTS=(/,/^)/p' lib/config.sh
declare -gA OPSCTL_DEFAULTS=(
  [env]=dev
  [data_dir]="$HOME/bashlab/data"
  [log_level]=info
  [output]=table
  [health_timeout]=5
  [health_retries]=4
  [health_expect]=200
  [backup_dir]="$HOME/bashlab/backups"
  [backup_keep]=7
  [deploy_root]="$HOME/bashlab/deploy"
  [deploy_keep]=5
  [deploy_health_url]=""
)

Why change config.sh instead of adding the defaults in the cmd file? Because config::init keys are parsed before dispatch etc/opsctl.conf, at which point the cmd files are not loaded yet, so keys not on the allowlist get a warning and are ignored. In opsctl.conf you can write backup_keep = 14, or use OPSCTL_BACKUP_KEEP=14 to override.

3. lib/cmd_health.sh

# shellcheck shell=bash
# opsctl-summary: HTTP health check with retries and backoff (health [-t SEC] [-r N] [-e CODE] URL)
# lib/cmd_health.sh — v0.3 (Lesson 6): curl probe + util::retry (exponential backoff + full jitter)
# Exit codes: 0 healthy · 1 still unhealthy after retries are exhausted · 2 usage error · 3 curl missing

health::usage() {
  cat <<EOF
Usage: ${OPSCTL_PROG:-opsctl} health [options] URL

Probe URL until it returns the expected HTTP status, retrying with
exponential backoff and full jitter (util::retry).

Options:
  -t, --timeout SEC    connect timeout; total per attempt is 2x (config: health_timeout)
  -r, --retries N      attempts in total (config: health_retries)
  -e, --expect CODE    expected HTTP status (config: health_expect)
  -h, --help           show this help
EOF
}

health::probe() {   # health::probe <url> <timeout> <expect>: one probe; returns 0 on success, otherwise 1
  local url=$1 timeout=$2 expect=$3 out code t rc=0
  out=$(curl -sS -o /dev/null -w '%{http_code} %{time_total}' \
    --connect-timeout "$timeout" --max-time "$((timeout * 2))" -- "$url") || rc=$?
  read -r code t <<<"${out:-000 0}"
  if ((rc == 0)) && [[ $code == "$expect" ]]; then
    log::info "health ok: $url code=$code time=${t}s"
    return 0
  fi
  log::warn "health fail: $url code=$code curl_rc=$rc"
  return 1
}

cmd::health() {
  local url="" timeout tries expect
  while (($#)); do
    case $1 in
      -t | --timeout | -r | --retries | -e | --expect)
        [[ $# -ge 2 && -n $2 ]] || util::usage_error "option '$1' requires an argument"
        case $1 in
          -t | --timeout) config::set_flag health_timeout "$2" ;;
          -r | --retries) config::set_flag health_retries "$2" ;;
          *) config::set_flag health_expect "$2" ;;
        esac
        shift 2 ;;
      -h | --help) health::usage; return 0 ;;
      --) shift; break ;;
      -*) util::usage_error "unknown option for 'health': $1" ;;
      *) [[ -z $url ]] || util::usage_error "unexpected argument: $1"; url=$1; shift ;;
    esac
  done
  if (($#)); then   # arguments after "--" (used when the URL starts with -)
    [[ -z $url && $# -eq 1 ]] || util::usage_error "unexpected argument(s): $*"
    url=$1
  fi
  [[ -n $url ]] || util::usage_error "missing URL"
  [[ $url =~ ^https?:// ]] || util::usage_error "URL must start with http:// or https://: $url"
  config::get health_timeout timeout || return 1
  config::get health_retries tries || return 1
  config::get health_expect expect || return 1
  [[ $timeout =~ ^[1-9][0-9]*$ && $tries =~ ^[1-9][0-9]*$ && $expect =~ ^[1-5][0-9][0-9]$ ]] \
    || util::usage_error "invalid timeout/retries/expect: $timeout/$tries/$expect"
  util::require_cmd curl

  # util::retry handles backoff and the "giving up" log; on failure it returns 1 (business failure; the caller decides whether to roll back)
  util::retry "$tries" 1 health::probe "$url" "$timeout" "$expect" || return 1
}

Design: health::probe It only does “one probe + log”: returns 0 on success, 1 on failure. Retries, exponential backoff, full jitter, and the “giving up” log are all delegated to util::retry <tries> <delay> <cmd…> from Lesson 4. util::retry Exit codes 2, 126 and 127 are treated as non-retryable, and since probe returns only 0 or 1, it won't misjudge. out=$(curl …) || rc=$? It runs in a conditional context, so it won't trigger the ERR trap's call-stack report.

4. lib/cmd_backup.sh

# shellcheck shell=bash
# opsctl-summary: archive a directory with checksum and rotation (backup [-o DIR] [-k N] SRC_DIR)
# lib/cmd_backup.sh — v0.3 (Lesson 6): util::lock → mktemp in the same directory → tar → verify → atomic mv → sha256 → rotate

backup::usage() {
  cat <<EOF
Usage: ${OPSCTL_PROG:-opsctl} backup [options] SRC_DIR

Create <out_dir>/<name>-YYYYmmddTHHMMSSZ.tar.gz (+ .sha256) atomically,
then keep only the newest N archives of that name.

Options:
  -o, --out-dir DIR    where archives go (config: backup_dir)
  -k, --keep N         archives to keep, N >= 1 (config: backup_keep)
  -h, --help           show this help
EOF
}

cmd::backup() {
  local src="" outdir keep
  while (($#)); do
    case $1 in
      -o | --out-dir | -k | --keep)
        [[ $# -ge 2 && -n $2 ]] || util::usage_error "option '$1' requires an argument"
        if [[ $1 == -o || $1 == --out-dir ]]; then config::set_flag backup_dir "$2"; else config::set_flag backup_keep "$2"; fi
        shift 2 ;;
      -h | --help) backup::usage; return 0 ;;
      -*) util::usage_error "unknown option for 'backup': $1" ;;
      *) [[ -z $src ]] || util::usage_error "unexpected argument: $1"; src=$1; shift ;;
    esac
  done
  [[ -n $src ]] || util::usage_error "missing SRC_DIR"
  [[ -d $src ]] || util::usage_error "not a directory: $src"
  config::get backup_dir outdir || return 1
  config::get backup_keep keep || return 1
  [[ $keep =~ ^[1-9][0-9]*$ ]] || util::usage_error "keep must be a positive integer: $keep"
  util::require_cmd tar sha256sum

  src=$(cd -- "$src" && pwd)
  mkdir -p -- "$outdir"
  util::lock backup                             # only one backup may run at a time (the v0.2 lock)

  local name ts final tmp base old
  name=${src##*/}
  ts=$(date -u +%Y%m%dT%H%M%SZ)
  final=$outdir/$name-$ts.tar.gz
  base=${final##*/}
  tmp=$(mktemp "$outdir/.$name.XXXXXX.part")    # same directory → mv is an atomic rename(2)
  util::cleanup_add "$tmp"                      # removed by the EXIT trap on failure or signal; no longer exists after mv

  tar -C "$(dirname -- "$src")" -czf "$tmp" -- "$name"
  tar -tzf "$tmp" >/dev/null                    # give it its final name only once the archive is readable
  mv -f -- "$tmp" "$final"
  (cd -- "$outdir" && sha256sum -- "$base" >"$base.sha256")
  log::info "backup created: $final ($(du -h -- "$final" | cut -f1))"

  # rotation: the names contain UTC timestamps → reverse order runs newest to oldest; skip the newest keep ones
  while IFS= read -r -d '' old; do
    rm -f -- "$old" "$old.sha256"
    log::info "rotated: $old"
  done < <(find "$outdir" -maxdepth 1 -type f -name "$name-*.tar.gz" -print0 | sort -z -r | tail -z -n +"$((keep + 1))")
}

Compared with the standalone script in Module 5: the lock now uses util::lock backup (var/lock/backup.lock, and when busy it util::die exits with 1); temp files are handed to util::cleanup_add, no longer trap … EXIT; temp files still use mktemp "$outdir/…" placed in the target directory, not in util::mktemp_dir 's /tmp— only mv within the same filesystem is an atomic rename(2).

5. lib/cmd_deploy.sh

# shellcheck shell=bash
# opsctl-summary: atomic release switch with health check and rollback (deploy -a PKG [-u URL] | --rollback)
# lib/cmd_deploy.sh — v0.3 (Lesson 6): <root>/releases/<UTC timestamp>/ + <root>/current -> releases/<timestamp>

deploy::usage() {
  cat <<EOF
Usage: ${OPSCTL_PROG:-opsctl} deploy -a PKG.tar.gz [options]
       ${OPSCTL_PROG:-opsctl} deploy --rollback [-d DIR]

Unpack PKG into <root>/releases/<timestamp>, switch <root>/current atomically,
run the health check, roll back automatically if it fails, prune old releases.

Options:
  -a, --artifact PKG   release tarball (must contain version.txt)
  -d, --root DIR       deploy root (config: deploy_root)
  -u, --url URL        health check URL (config: deploy_health_url; empty = skip)
  -k, --keep N         releases to keep, N >= 1 (config: deploy_keep)
      --rollback       switch current back to the previous release
  -h, --help           show this help
EOF
}

deploy::switch() {   # deploy::switch <root> <target>: temp link + rename(2), atomically replaces current
  ln -sfn -- "$2" "$1/.current.tmp"
  mv -Tf -- "$1/.current.tmp" "$1/current"     # GNU mv -T: treats current as a file, not as the target directory
}

deploy::previous() { # deploy::previous <root>: prints the release before current (sorted by name); returns 1 if none
  local root=$1 cur rel prev=""
  cur=$(readlink -- "$root/current") || return 1
  while IFS= read -r rel; do
    if [[ releases/$rel == "$cur" ]]; then
      [[ -n $prev ]] || return 1
      printf 'releases/%s\n' "$prev"
      return 0
    fi
    prev=$rel
  done < <(find "$root/releases" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort)
  return 1
}

cmd::deploy() {
  local artifact="" rollback=0 root url keep
  while (($#)); do
    case $1 in
      -a | --artifact | -d | --root | -u | --url | -k | --keep)
        [[ $# -ge 2 && -n $2 ]] || util::usage_error "option '$1' requires an argument"
        case $1 in
          -a | --artifact) artifact=$2 ;;
          -d | --root) config::set_flag deploy_root "$2" ;;
          -u | --url) config::set_flag deploy_health_url "$2" ;;
          *) config::set_flag deploy_keep "$2" ;;
        esac
        shift 2 ;;
      --rollback) rollback=1; shift ;;
      -h | --help) deploy::usage; return 0 ;;
      *) util::usage_error "unknown argument for 'deploy': $1" ;;
    esac
  done
  config::get deploy_root root || return 1
  config::get deploy_health_url url || return 1
  config::get deploy_keep keep || return 1
  [[ $keep =~ ^[1-9][0-9]*$ ]] || util::usage_error "keep must be a positive integer: $keep"
  mkdir -p -- "$root/releases"
  util::lock deploy                             # two deploys running at once = disaster

  if ((rollback)); then
    local prev
    prev=$(deploy::previous "$root") || util::die "no previous release to roll back to"
    deploy::switch "$root" "$prev"
    log::warn "rolled back: current -> $prev"
    return 0
  fi

  [[ -n $artifact ]] || util::usage_error "missing -a PKG.tar.gz"
  [[ -f $artifact ]] || util::usage_error "artifact not found: $artifact"
  util::require_cmd tar
  if [[ -n $url ]]; then   # the dispatcher only loads cmd_deploy.sh; load health by name before reusing it
    opsctl::load_command health || util::die "cannot load lib/cmd_health.sh"
  fi

  local ts rel old cur r
  ts=$(date -u +%Y%m%dT%H%M%SZ)
  rel=$root/releases/$ts
  [[ ! -e $rel ]] || util::die "$rel already exists (two deploys within one second?)"
  mkdir -p -- "$rel"
  tar -xzf "$artifact" -C "$rel"
  if [[ ! -f $rel/version.txt ]]; then
    rm -rf -- "${rel:?}"
    util::die "artifact has no version.txt, aborted (current unchanged)"
  fi
  old=$(readlink -- "$root/current" || true)

  deploy::switch "$root" "releases/$ts"
  log::info "switched: current -> releases/$ts (previous: ${old:-none}) version $(<"$rel/version.txt")"

  if [[ -n $url ]] && ! cmd::health -r 3 -t 2 "$url"; then
    if [[ -n $old ]]; then
      deploy::switch "$root" "$old"
      log::error "health check failed, rolled back: current -> $old"
    else
      log::error "health check failed and there is no previous release"
    fi
    return 1
  fi

  # cleanup: keep the newest keep releases, never delete the one current points to
  cur=$(readlink -- "$root/current")
  while IFS= read -r r; do
    [[ releases/$r == "$cur" ]] && continue
    rm -rf -- "${root:?}/releases/${r:?}"
    log::info "pruned: releases/$r"
  done < <(find "$root/releases" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort -r | tail -n +"$((keep + 1))")
  log::info "deploy ok: releases/$ts"
}

Key points: ① opsctl::load_command health (functions in bin/opsctl) load health when needed; ② ! cmd::health -r 3 -t 2 "$url" runs in a conditional context, so a failure inside health does not trigger errexit / ERR reporting; ③ release directory names are generated by the script, so a plain find -printf '%f\n' ls listing is enough; ④ "${rel:?}" prevents an empty variable from causing rm -rf an accidental deletion.

6. (Optional) make opsctl config show the new keys

sed -i 's/^      for key in env data_dir log_level output; do$/      for key in env data_dir log_level output health_timeout health_retries health_expect backup_dir backup_keep deploy_root deploy_keep deploy_health_url; do/' lib/cmd_config.sh
OPSCTL_BACKUP_KEEP=14 bin/opsctl config
KEY        VALUE                        SOURCE
env        dev                          file ~/bashlab/opsctl/etc/opsctl.conf
data_dir   ~/bashlab/data               file ~/bashlab/opsctl/etc/opsctl.conf
log_level  info                         file ~/bashlab/opsctl/etc/opsctl.conf
output     table                        file ~/bashlab/opsctl/etc/opsctl.conf
health_timeout 5                            default
health_retries 4                            default
health_expect 200                          default
backup_dir ~/bashlab/backups            default
backup_keep 14                           env OPSCTL_BACKUP_KEEP
deploy_root ~/bashlab/deploy             default
deploy_keep 5                            default
deploy_health_url                              default

Lesson 3's cmd::config uses a fixed key list; this step just completes the list (the column width was designed for 4 short keys, so long keys will be misaligned, but that does not affect functionality).

7. Help and discovery (actual run)

export NO_COLOR=1
bin/opsctl -V
bin/opsctl --help | sed -n '/^Commands:/,/^  help/p'
bin/opsctl help health; echo "rc=$?"
opsctl 0.3.0
Commands:
  backup           archive a directory with checksum and rotation (backup [-o DIR] [-k N] SRC_DIR)
  config           show effective configuration and where each value came from
  deploy           atomic release switch with health check and rollback (deploy -a PKG [-u URL] | --rollback)
  doctor           check bash version, dependencies, data and lock dirs (read-only)
  export           export servers.csv atomically (export servers --out FILE [--env ENV])
  health           HTTP health check with retries and backoff (health [-t SEC] [-r N] [-e CODE] URL)
  servers          query the server inventory (servers list --env ENV)
  help [COMMAND]   show help for a command
Usage: opsctl health [options] URL

Probe URL until it returns the expected HTTP status, retrying with
exponential backoff and full jitter (util::retry).

Options:
  -t, --timeout SEC    connect timeout; total per attempt is 2x (config: health_timeout)
  -r, --retries N      attempts in total (config: health_retries)
  -e, --expect CODE    expected HTTP status (config: health_expect)
  -h, --help           show this help
rc=0

8. health (actual run; mockapi running on 8000)

B=http://127.0.0.1:8000
bin/opsctl health; echo "rc=$?"
bin/opsctl health "$B/flaky?fail=2&key=h"; echo "rc=$?"
bin/opsctl health -r 2 "$B/status/500"; echo "rc=$?"
2026-11-17T03:01:27-0500 ERROR opsctl[22796]: missing URL
Try 'opsctl --help' for more information.
rc=2
2026-11-17T03:01:28-0500 WARN  opsctl[22811]: health fail: http://127.0.0.1:8000/flaky?fail=2&key=h code=503 curl_rc=0
2026-11-17T03:01:28-0500 WARN  opsctl[22811]: attempt 1/4 failed (exit 1), retrying in 0.677s
2026-11-17T03:01:28-0500 WARN  opsctl[22811]: health fail: http://127.0.0.1:8000/flaky?fail=2&key=h code=503 curl_rc=0
2026-11-17T03:01:28-0500 WARN  opsctl[22811]: attempt 2/4 failed (exit 1), retrying in 1.037s
2026-11-17T03:01:29-0500 INFO  opsctl[22811]: health ok: http://127.0.0.1:8000/flaky?fail=2&key=h code=200 time=0.002314s
2026-11-17T03:01:29-0500 INFO  opsctl[22811]: attempt 3 succeeded: health::probe http://127.0.0.1:8000/flaky?fail=2&key=h 5 200
rc=0
2026-11-17T03:01:29-0500 WARN  opsctl[22826]: health fail: http://127.0.0.1:8000/status/500 code=500 curl_rc=0
2026-11-17T03:01:29-0500 WARN  opsctl[22826]: attempt 1/2 failed (exit 1), retrying in 0.381s
2026-11-17T03:01:30-0500 WARN  opsctl[22826]: health fail: http://127.0.0.1:8000/status/500 code=500 curl_rc=0
2026-11-17T03:01:30-0500 ERROR opsctl[22826]: giving up after 2 attempts (exit 1): health::probe http://127.0.0.1:8000/status/500 5 200
rc=1

“Full jitter”: after the nth failure, wait random(0, min(30, 1×2^(n-1))) seconds, so the second wait can also be shorter than the first. The cap is controlled by RETRY_MAX_DELAY (default 30).

9. backup and deploy (actual run, excerpt, paths abbreviated to ~)

for i in 1 2 3; do bin/opsctl backup -k 2 ~/bashlab/data; sleep 1.1; done
( flock var/lock/backup.lock sleep 3 ) & sleep 0.5
bin/opsctl backup ~/bashlab/data; echo "lock rc=$?"; wait
bin/opsctl backup /nonexistent; echo "rc=$?"
2026-11-17T03:01:35-0500 INFO  opsctl[22857]: backup created: ~/bashlab/backups/data-20261117T080135Z.tar.gz (4.0K)
2026-11-17T03:01:36-0500 INFO  opsctl[22887]: backup created: ~/bashlab/backups/data-20261117T080136Z.tar.gz (4.0K)
2026-11-17T03:01:37-0500 INFO  opsctl[22917]: backup created: ~/bashlab/backups/data-20261117T080137Z.tar.gz (4.0K)
2026-11-17T03:01:37-0500 INFO  opsctl[22917]: rotated: ~/bashlab/backups/data-20261117T080135Z.tar.gz
2026-11-17T03:01:38-0500 ERROR opsctl[22955]: lock busy: ~/bashlab/opsctl/var/lock/backup.lock (another opsctl running?)
lock rc=1
2026-11-17T03:01:41-0500 ERROR opsctl[22963]: not a directory: /nonexistent
Try 'opsctl --help' for more information.
rc=2
for v in 1.0.0 1.1.0 1.2.0; do
  bin/opsctl deploy -a ~/bashlab/m4/app-$v.tar.gz -u http://127.0.0.1:8080/healthz -k 3
  echo "deploy $v rc=$?  serving=$(curl -s http://127.0.0.1:8080/version.txt)"; sleep 1.1
done
bin/opsctl deploy --rollback; echo "rb rc=$?"; curl -s http://127.0.0.1:8080/version.txt
2026-11-17T03:02:29-0500 INFO  opsctl[23414]: switched: current -> releases/20261117T080229Z (previous: none) version 1.0.0
2026-11-17T03:02:29-0500 INFO  opsctl[23414]: health ok: http://127.0.0.1:8080/healthz code=200 time=0.003412s
2026-11-17T03:02:29-0500 INFO  opsctl[23414]: deploy ok: releases/20261117T080229Z
deploy 1.0.0 rc=0  serving=1.0.0
2026-11-17T03:02:30-0500 INFO  opsctl[23442]: switched: current -> releases/20261117T080230Z (previous: releases/20261117T080229Z) version 1.1.0
2026-11-17T03:02:30-0500 INFO  opsctl[23442]: health ok: http://127.0.0.1:8080/healthz code=200 time=0.000824s
2026-11-17T03:02:30-0500 INFO  opsctl[23442]: deploy ok: releases/20261117T080230Z
deploy 1.1.0 rc=0  serving=1.1.0
2026-11-17T03:02:31-0500 INFO  opsctl[23470]: switched: current -> releases/20261117T080231Z (previous: releases/20261117T080230Z) version 1.2.0
2026-11-17T03:02:31-0500 WARN  opsctl[23470]: health fail: http://127.0.0.1:8080/healthz code=404 curl_rc=0
2026-11-17T03:02:31-0500 WARN  opsctl[23470]: attempt 1/3 failed (exit 1), retrying in 0.665s
2026-11-17T03:02:32-0500 WARN  opsctl[23470]: health fail: http://127.0.0.1:8080/healthz code=404 curl_rc=0
2026-11-17T03:02:32-0500 WARN  opsctl[23470]: attempt 2/3 failed (exit 1), retrying in 1.817s
2026-11-17T03:02:34-0500 WARN  opsctl[23470]: health fail: http://127.0.0.1:8080/healthz code=404 curl_rc=0
2026-11-17T03:02:34-0500 ERROR opsctl[23470]: giving up after 3 attempts (exit 1): health::probe http://127.0.0.1:8080/healthz 2 200
2026-11-17T03:02:34-0500 ERROR opsctl[23470]: health check failed, rolled back: current -> releases/20261117T080230Z
deploy 1.2.0 rc=1  serving=1.1.0
2026-11-17T03:02:35-0500 WARN  opsctl[23506]: rolled back: current -> releases/20261117T080229Z
rb rc=0
1.0.0

The bad-version directory releases/20261117T080231Z is kept for troubleshooting; on the next successful deploy, it is cleaned up per -k .

Lab: complete opsctl v0.3 on top of v0.2.0 and self-test it

Environment: ~/bashlab/opsctl You should be in the v0.2.0 from Lesson 4 (Module 0, step 3); mockapi is running on 8000; the three Module 4 packages are in ~/bashlab/m4/.
cd ~/bashlab/opsctl && git status --short && git describe --tags
export NO_COLOR=1 PATH="$HOME/bashlab/opsctl/bin:$PATH"
Edit and add: follow steps 1–5 on the “Commands” tab: bump the version number, extend OPSCTL_DEFAULTS, add lib/cmd_health.sh,lib/cmd_backup.sh,lib/cmd_deploy.sh (line 2 of each file is # opsctl-summary:). Then check:
for f in bin/opsctl lib/*.sh; do bash -n "$f" || echo "SYNTAX FAIL: $f"; done
grep -H '^# opsctl-summary:' lib/cmd_*.sh | wc -l        # 7: servers config export doctor + 3 new commands
command -v shellcheck >/dev/null && shellcheck -x bin/opsctl lib/*.sh
opsctl -V && opsctl help deploy | head -3
health:
opsctl health http://127.0.0.1:8000/healthz; echo "rc=$?"                       # 0
opsctl health -r 4 "http://127.0.0.1:8000/flaky?fail=2&key=lab8"; echo "rc=$?"   # 0 (succeeds on 3rd try)
opsctl health -r 2 -t 1 "http://127.0.0.1:8000/slow?sec=5"; echo "rc=$?"          # 1 (2-second timeout each time)
OPSCTL_HEALTH_RETRIES=1 opsctl health http://127.0.0.1:8000/status/503; echo "rc=$?"  # 1, only tries once (env var takes effect)
opsctl health -x http://127.0.0.1:8000/healthz; echo "rc=$?"                     # 2 (unknown option)

Want to see exit code 3? Temporarily hiding curl without affecting bash itself is hard — Lesson 7 uses bats to build a PATH that is missing only curl, for testing util::require_cmd.

backup:
for i in 1 2 3; do opsctl backup -k 2 ~/bashlab/data; sleep 1.1; done
ls -1 ~/bashlab/backups | grep -c 'tar.gz$'                  # 2
(cd ~/bashlab/backups && sha256sum -c ./*.sha256)
ls -A ~/bashlab/backups | grep -c part                        # 0: no leftover temp files
deploy:
mkdir -p ~/bashlab/deploy
python3 -m http.server 8080 --bind 127.0.0.1 -d ~/bashlab/deploy/current >/dev/null 2>&1 & echo $! > /tmp/http8080.pid
for v in 1.0.0 1.1.0 1.2.0; do
  opsctl deploy -a ~/bashlab/m4/app-$v.tar.gz -u http://127.0.0.1:8080/healthz -k 3
  echo "deploy $v rc=$?  serving=$(curl -s http://127.0.0.1:8080/version.txt)"; sleep 1.1
done
opsctl deploy --rollback; curl -s http://127.0.0.1:8080/version.txt
deploy 1.0.0 rc=0  serving=1.0.0
deploy 1.1.0 rc=0  serving=1.1.0
deploy 1.2.0 rc=1  serving=1.1.0
1.0.0
Smoke test: run the Module 7 test/smoke.sh, expecting the last line to be SMOKE OK (verified in a real run).
Submit and clean up:
kill "$(cat /tmp/http8080.pid)"; rm -f /tmp/http8080.pid
rm -rf ~/bashlab/deploy                          # keep backups and opsctl
cd ~/bashlab/opsctl && git add -A && git commit -m "opsctl v0.3: health, backup, deploy" && git tag v0.3.0
kill "$(cat ~/bashlab/mock/mock.pid)"            # stop mockapi when the course ends

Case 1: consolidating three “legacy” scripts with opsctl

Problem: The team has check_web.sh,bk.sh, and release.sh scripts from different authors: one returns 0 on failure, one writes its logs to stdout and floods cron email, and one exit which kills the caller. Approach: Unified as opsctl subcommands: logs go to stderr, business failure return 1, usage error 2, dependency 3; systemd timers and CI only call opsctl …. Limitations: During migration, keep the old scripts as thin wrappers around opsctl to avoid a big-bang cutover.

Case 2: a config file was executed as a script

Problem: Another team's tool runs its config file directly with source, and someone wrote DEPLOY_ROOT=$(curl …), so every run hits the network, and even help fails. Approach: Since Lesson 3, opsctl has used config::load_file a parser that matches key = value keys against a whitelist and never sources the file — so v0.3's new keys must be registered in OPSCTL_DEFAULTS (otherwise they are warned about and ignored), which is why step 2 on the “Commands” tab exists. Limitations: Parse-only config files do not support variables or command substitution; for dynamic values, use environment variables OPSCTL_<KEY> or pass them as command-line options.

Case 3: deploy reuses health and produces “double logs”

Problem: deploy calls health; on failure, health logs one ERROR and deploy logs another, so the alerting system doubles its ERROR count. Approach: Convention: “the outermost caller decides on ERROR”: called functions log each attempt at WARN and report results via return values; or add a quiet parameter. Limitations: The log-level convention must be written into the README; the Lesson 7 tests can assert on log content.

Interactive troubleshooting tree (this lesson's topic)

Start from the symptom, make choices step by step, and get the diagnosis and fix commands.

Quick reference for common errors

ERROR opsctl[…]: unknown command: health (lib/cmd_health.sh already exists)

Cause:opsctl::load_command Requirements: the file name lib/cmd_health.sh, readable, sourceable (no syntax errors), and defines cmd::health. If any one of these is not met, you get unknown command (exit code 2).

bash -n lib/cmd_health.sh; grep -n '^cmd::' lib/cmd_health.sh; ls -l lib/cmd_health.sh
The new command shows no description in opsctl --help

Cause: Missing # opsctl-summary: … comment line (note the space after the colon,opsctl::list_commands matched by the prefix '# opsctl-summary: ' ).

grep -H '^# opsctl-summary: ' lib/cmd_*.sh
cmd_deploy.sh: line …: cmd::health: command not found, followed by “health check failed, rolled back”

Cause: The dispatcher only loads the cmd file that was called. Before deploy reuses health, it must load opsctl::load_command health (a pitfall we hit while writing this lesson: when not loaded, ! cmd::health returns 127, which is treated as “unhealthy”, so every deploy gets rolled back).

WARN … etc/opsctl.conf:7: unknown key 'backup_keep' (ignored)

Cause: The new key was not added to lib/config.sh the OPSCTL_DEFAULTS,config::load_file so the allowlist ignored it.

Fix: Insert the key per step 2 on the “Commands” tab; use opsctl config (optional step 6) to confirm the source column shows file ….

ERROR opsctl[…]: lock busy: ~/bashlab/opsctl/var/lock/backup.lock (another opsctl running?)

Cause: Another opsctl backup (for example, the timer-triggered run) is still running; or you sourced the library in an interactive shell and called util::lock, so the fd is still open.

fuser -v ~/bashlab/opsctl/var/lock/backup.lock; pgrep -af 'opsctl backup'

Fix: Wait, or investigate the stuck process; run bin/opsctl as a separate process, which releases the lock on exit. When you need to queue, call util::lock backup 60 (waits 60 seconds).

Command-line exercises
1. Add an health environment variable override to opsctl: without changing code, make one call expect status 204 and retry at most 6 times.
OPSCTL_HEALTH_EXPECT=204 OPSCTL_HEALTH_RETRIES=6 opsctl health https://api.example.com/ping
# or put it in etc/opsctl.conf: health_expect = 204 (priority: flag > env > file > default)
# or: opsctl health -e 204 -r 6 https://api.example.com/ping
2. Write an ExecStart line for a systemd service that deploys /srv/pkgs/app-latest.tar.gz to /srv/app and use http://127.0.0.1:8080/healthz to check.
ExecStart=/opt/opsctl/bin/opsctl deploy -a /srv/pkgs/app-latest.tar.gz -d /srv/app -u http://127.0.0.1:8080/healthz
Scenario analysis
You need to add opsctl report: call 3 APIs (each one paginated), aggregate the results, and output Markdown. How would you design the files, functions, and exit codes?

Files lib/cmd_report.sh, functions cmd::report; put the generic paginated GET into lib/api.sh (api::get_all URL, Module 1); dependencies util::require_cmd curl jq the three APIs can run in parallel as background jobs (results written to a temp directory,wait collect exit codes); if any API fails, output a partial report plus WARN and exit with code 1 (so CI goes red); usage error 2; all curl calls have timeouts and bounded retries; Markdown goes to stdout and logs go to stderr, which makes it easy to opsctl report > report.md; in Lesson 7, write bats tests for api::get_all (using mockapi).

Verified teaching videos

opsctl is a project built for this course, so there is no matching public video. The videos below relate to parts of this module (all verified via YouTube oEmbed):

▶
mastering the curl command line - with Daniel Stenberg — Daniel Stenberg
English · the curl knowledge behind the health subcommand
▶
Automate Your Tasks with systemd Timers: A Step-by-Step Guide — Learn Linux TV
English · scheduling opsctl backup with a timer

Official docs and specs

Video storyboard (about 90 seconds)

This lesson cannot directly generate a video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: three scattered script icons are sucked into an opsctl toolbox with three drawers labeled health, backup, and deploy.
Narration: Gather scattered scripts into one tool: unified logging, exit codes, and configuration.
Shot 2 · 20–50s
Visual: the entry point bin/opsctl loads lib, finds cmd::deploy and calls it; deploy in turn calls cmd::health.
Narration: The entry point only dispatches. Subcommands can be reused, for example deploy calling the health check directly.
Shot 3 · 50–75s
Visual: the exit code table 0, 1, 2, 3 lights up in turn, with three callers next to it: cron, systemd, and CI.
Narration: Zero means success, one means business failure, two means usage error, three means a missing dependency. Callers decide from this whether to alert or retry.
Shot 4 · 75–90s
Visual: a terminal runs smoke.sh, and the last line is SMOKE OK.
Narration: Finally, a smoke test verifies v0.3. In the next lesson we add bats tests and ShellCheck, and release 1.0.
or score ≥ 70% on the Quiz

Command cheat sheet

The high-frequency patterns from all 8 modules of this course, on one page
PrintablePatterns verified on Bash 5.2 / curl 8.5 are marked in each module
1 · Calling APIs with curl
curl -fsS --connect-timeout 3 --max-time 10 \
     --retry 4 --retry-max-time 60 --retry-connrefused "$url"
curl -sS --fail-with-body "$url"            # 22 + keep error body (7.76+)
code=$(curl -sS -o body -w '%{http_code}' "$url") || code=000
curl -sS -o /dev/null -w '%header{link}\n' "$url"   # 7.84+
jq -n --arg n web '{name:$n}' | curl -sS --json @- "$api"   # 7.82+
2 · Link pagination
while [[ -n $url ]]; do
  body=$(curl -fsS -D "$hdr" "$url")
  jq -c '.[]' <<<"$body"
  url=$(tr -d '\r' <"$hdr" |
    sed -n 's/^[Ll]ink:.*<\([^>]*\)>; *rel="next".*/\1/p')
done
3 · Reading values from az / aws
export AWS_PAGER="" AZURE_CORE_OUTPUT=json
sub=$(az account show --query id -o tsv)
az vm list -d --query "[?powerState=='VM running'].[name,resourceGroup]" -o tsv
aws sts get-caller-identity --query Account --output text
aws ec2 describe-instances --filters Name=instance-state-name,Values=running \
  --query 'Reservations[].Instances[].[InstanceId,PrivateIpAddress]' --output text
# aws rc: 252 syntax · 253 credentials/config · 254 server error · 255 other
4 · jq → Bash
while IFS=$'\t' read -r id name ip; do …; done \
  < <(jq -r '.[] | [.id, (.name // "-"), .ip] | @tsv' f.json)
mapfile -t ids < <(jq -r '.[].id' f.json)
jq -e '.items | length > 0' f.json >/dev/null || echo "empty"
jq -r --arg env prod '.[] | select(.env==$env) | .name' f.json
5 · Parallelism and SSH
ssh -n -o BatchMode=yes -o ConnectTimeout=5 \
    -o StrictHostKeyChecking=accept-new "$h" cmd
xargs -0 -P 4 -n 2 bash -c 'f "$1" "$2"' _     # export -f f
parallel -j 8 --tag --timeout 60 --joblog jobs.tsv \
  ssh -n -o BatchMode=yes {} uptime :::: hosts.txt
# xargs: any failure → 123; parallel → number of failed jobs
6 · Atomic deploy and rollback
ts=$(date -u +%Y%m%dT%H%M%SZ)
mkdir -p releases/$ts && tar -xzf app.tgz -C releases/$ts
prev=$(readlink current || true)
ln -sfn releases/$ts .current.tmp && mv -Tf .current.tmp current
opsctl health -r 3 "$url" || { ln -sfn "$prev" .current.tmp; mv -Tf .current.tmp current; exit 1; }
7 · Backup and rotation
exec 9>"$dest/.lock"; flock -n 9 || exit 1
tmp=$(mktemp "$dest/.x.XXXXXX.part"); trap 'rm -f -- "$tmp"' EXIT
tar -C "$(dirname "$src")" -czf "$tmp" -- "$(basename "$src")"
tar -tzf "$tmp" >/dev/null && mv -f -- "$tmp" "$final"
(cd "$dest" && sha256sum -- "${final##*/}" > "${final##*/}.sha256")
find "$dest" -maxdepth 1 -name 'x-*.tar.gz' -print0 | sort -z -r | tail -z -n +8 |
  while IFS= read -r -d '' f; do rm -f -- "$f" "$f.sha256"; done
8 · cron / systemd timer / CI
# crontab: PATH=… ; write % as \%
0 2 * * * flock -n /tmp/b.lock opsctl backup "$HOME/data" >>"$HOME/b.log" 2>&1
# .timer
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
RandomizedDelaySec=10min
systemd-analyze calendar '*-*-* 02:00:00'
systemctl --user enable --now x.timer; loginctl enable-linger "$USER"
# GitHub Actions: defaults.run.shell: bash  → -eo pipefail
# GitLab: resource_group: production; artifacts: when: always

Quick troubleshooting table

SymptomMost likely causeFirst commandModule
curl returns 0 but jq reports parse errorHTTP error page with no -fcurl -sS -D - -o /dev/null "$url"1
rc=28Timeout (connect or total duration)curl -w 'connect=%{time_connect} ttfb=%{time_starttransfer}'1
Pagination loop / second page returns 400URL ends with \rprintf '%q\n' "$url"1
Variable value contains quotes / bracketsaz / aws output JSONAdd -o tsv / --output text2
aws command hangs in CIv2 paginatorexport AWS_PAGER=""2
loop only processes the first hostssh consumed stdinssh -n3
xargs rc=123at least one job failedCheck each job's .rc / joblog3
current unchanged after switchmv Missing -Tls -lA "$(readlink -f current)"4
Intermittent 404 during deployNon-atomic switch: delete first, then createSwitch to a temp link + mv -T4
Half-written file in the backup directoryWriting directly to the final nametemp .part + mv5
command not found in cronTrim PATH* * * * * env > /tmp/cron-env6
Timer never firesOnly enabled the .servicesystemctl --user list-timers --all6
CI shows success despite a failureNo pipefail / || trueIn YAML, add shell: bash7
Process completed with exit code 141pipefail + SIGPIPEuse sed -n 1p instead of head -17

Recommended config snippets

~/.curlrc (interactive use only; in scripts, ignore it with -q)
--connect-timeout 5
--max-time 60
--show-error
--fail-with-body

In scripts, put -q (--disable), which ignores curlrc and keeps behavior predictable.

~/.ssh/config (for batch operations)
Host 10.0.* web-* api-*
  BatchMode yes
  ConnectTimeout 5
  StrictHostKeyChecking accept-new
  ServerAliveInterval 15
  ControlMaster auto
  ControlPath ~/.ssh/cm-%C
  ControlPersist 5m

Capstone lab + final quiz

End to end: fetch inventory → parallel health checks → backup → deploy (including one automatic rollback) → scheduling → CI smoke test
About 30–40 minutesZero costopsctl v0.3

Scenario

You are responsible for a small internal service myapp (this lesson uses a static directory + python3 -m http.server instead). Release requirements: ① fetch the instance list from the “inventory API” (mockapi's /items, paginated), ② check each instance's health endpoint in parallel and abort if more than one fails; ③ back up the current release directory before deploying; ④ deploy the new version, with automatic rollback if the health check fails; ⑤ back up daily on a schedule; ⑥ run the smoke test in CI. Use opsctl v0.3 and this lesson's patterns for all steps.

Setup: mockapi is running on 8000; opsctl is v0.3; the three Module 4 packages exist. Create ~/bashlab/final.
mkdir -p ~/bashlab/final && cd ~/bashlab/final
export PATH="$HOME/bashlab/opsctl/bin:$PATH"; opsctl version
curl -fsS http://127.0.0.1:8000/healthz
Fetch the inventory (paginated): use the Module 1 api::get_all to fetch all 23 instances, save them as JSON Lines, and verify the count equals the response header X-Total-Count.
source ~/bashlab/final/api.sh      # contains api::get_all (copied from Module 1)
api::get_all 'http://127.0.0.1:8000/items?per_page=10' > inventory.jsonl
want=$(curl -sS -o /dev/null -D - 'http://127.0.0.1:8000/items' | tr -d '\r' | awk -F': ' 'tolower($1)=="x-total-count"{print $2}')
got=$(wc -l < inventory.jsonl); [[ $got == "$want" ]] && echo "inventory complete: $got" || { echo "inventory incomplete $got/$want"; exit 1; }
Parallel health checks: generate URLs for the first 6 instances (one of which points to /status/503), using xargs -P 4 to call opsctl health -r 2 -t 2, writing each result to results/, count failures,and abort when failures > 1.
mkdir -p results
jq -r '.name' inventory.jsonl | head -6 | awk '{u = (NR==3) ? "/status/503" : "/healthz"; print $1 "\t" "http://127.0.0.1:8000" u}' > targets.tsv
tr '\t\n' '\0\0' < targets.tsv |
  xargs -0 -n 2 -P 4 bash -c 'opsctl health -r 2 -t 2 "$2" 2>"results/$1.log"; echo $? > "results/$1.rc"' _
fails=$(grep -lvx 0 results/*.rc | wc -l); echo "failed instances: $fails"
((fails <= 1)) || { echo "too many failures, aborting release"; exit 1; }
Back up before deploying: if ~/bashlab/deploy/current exists, back up the release directory it points to (opsctl backup -o ~/bashlab/final/predeploy -k 3 "$(readlink -f ~/bashlab/deploy/current)"), and verify it with sha256sum -c .
Deploy and automatic rollback: start http.server on 8080, deploy 1.0.0, 1.1.0, and 1.2.0 (bad) in turn, record each run's exit code and the version actually served; finally confirm production is 1.1.0, then manually --rollback once, then deploy 1.1.0 to restore it.
Scheduling: use the Module 6 user-level opsctl-backup.timer (daily at 02:00 UTC, Persistent, random delay),systemd-analyze calendar and verify it; for environments without systemd, write an equivalent crontab (including flock and PATH).
CI smoke test: wire test/smoke.sh into GitHub Actions (shell: bash) or GitLab CI, deliberately make it fail once, and confirm the log artifacts are still uploaded.
Cleanup: stop the two Python processes on 8000 / 8080; rm -rf ~/bashlab/final ~/bashlab/deploy; if no longer needed,systemctl --user disable --now opsctl-backup.timer.
Acceptance checklist

Open-ended self-check (6 questions)

1. Why does this lesson's health check write its own retry loop, while “fetching data” uses curl's built-in --retry?

The built-in --retry only retries “transient errors” (timeouts, some 408/429/5xx responses), suits idempotent data fetches, and automatically honors Retry-After; health checks need to retry on any unexpected status code, log each attempt, add jitter, and let the caller (deploy) decide on rollback based on the result, so a hand-written loop fits better.

2. Explain ln -sfn new .current.tmp && mv -Tf .current.tmp current the effect of each option.

-s symbolic link; -f replace if it already exists; -n if the link name is a symlink to a directory, do not follow into it. mv -T treat the target as a regular file (otherwise it would move into the directory current points to); -f no prompt. Overall effect: prepare the new link under a temp name, then atomically replace the old one with a single rename(2).

3. Why is rotating by count safer than rotating by age? When do you still need age-based rotation?

If backups fail for a long time, age-based rotation gradually deletes all the old backups; count-based rotation always keeps the newest N. When compliance requires “retain no longer than X days” (for example, personal data), you need age-based deletion, and then you should pair it with monitoring of the “latest backup age”.

4. Why does a cron job stop overlapping its own runs after moving to a systemd timer? Is that always a good thing?

When the timer fires while the service unit is still active/activating, systemd does not start a second instance. This is usually good (it avoids contention), but if the job hangs and has no TimeoutStartSec, all later triggers are skipped, so you need a timeout and alerting.

5. In GitHub Actions, which patterns can make a failure turn green?

pipe failures go unnoticed when no shell is set (no pipefail) || true and continue-on-error: true failures in background processes are not wait; the script exits early on the CI branch with exit 0.

6. Which opsctl features would you run in CI, and which would you leave on host timers?

CI: deploy (needs approval, auditing, and serialization), cloud resource checks (short-lived OIDC credentials), and smoke tests. Host: local backups and minute-level health checks (they need internal network access and should keep running when CI is down). The key point is one opsctl with two scheduling methods.

Sources and version notes

Verified on 2026-11-17; anything that could not be verified is marked “refer to official documentation” or handled conservatively
Verified on 2026-11-17

Source table

TopicVerified findingSource (accessed 2026-11-17)
Latest curl version8.23.0 (2026-10-14)GitHub curl/curl Releases
curl options and versions--fail-with-body 7.76.0; --retry-all-errors 7.71.0; --json 7.82.0; --parallel 7.66.0 (default limit 50); %{header_json} 7.83.0; %header{} 7.84.0; %{num_retries} 8.9.0; %{exitcode}/%{errormsg} 7.75.0; --variable 8.3.0curl.se/docs/manpage.html
curl retry semanticsTransient errors: timeouts, FTP 4xx, HTTP 408/429/500/502/503/504/522/524; doubles from 1 second, capped at 10 minutes; Retry-After (7.66.0+); --retry-max-time no new retry starts after the deadlineSame as above (--retry and --retry-max-time entries)
curl exit codes22: HTTP ≥ 400 (-f); 28: timeoutSame as above (EXIT CODES)
Azure CLILatest 2.93.0 (2026-11-15); --query runs on the client side; read variable values using -o tsvGitHub Azure/azure-cli · Troubleshooting Azure CLI · Query
AWS CLI v2Latest 2.40.4 (2026-11-16); return codes 0/1/2/130/252/253/254/255; for text output, paginate first, then run --query on each pageaws-cli CHANGELOG · Return codes · Filtering output
jq / yq / ShellCheckjq 1.8.2; mikefarah yq v4.54.3; ShellCheck 0.11.0GitHub Releases: jqlang/jq, mikefarah/yq, koalaman/shellcheck
GNU parallelLatest 20261022ftp.gnu.org/gnu/parallel
Bash5.3 is the current release; the Docker official image bash:5.3 (5.3.20, Alpine 3.24) is availableftp.gnu.org/gnu/bash · Docker Hub bash
GitHub Actions shellNot specified: bash -e {0}; bash: bash --noprofile --norc -eo pipefail {0}; sh: sh -e {0}Workflow syntax
Actions versionsactions/checkout v7.0.1; actions/upload-artifact v7.0.2; azure/login v3.1.0; aws-actions/configure-aws-credentials v6.3.0GitHub Releases for each repository
GitLab CI scriptA non-zero exit code fails the job and the following commands do not run; when joined into one string, only the last command is reported; commands containing colons need quotesScripts and job logs
rename(2) atomicityif the new path already exists, it is atomically replacedrename(2)
systemd timersPersistent,RandomizedDelaySec,FixedRandomDelay; daily = 00:00 (tested on systemd 255)systemd.timer(5) · systemd.time(7)

Notes on local testing

The following was run for real on WSL2 Ubuntu 24.04.1 (Bash 5.2.21, curl 8.5.0, GNU coreutils 9.4, Python 3.12.3, systemd 255), with output labeled “Actual output”: all mockapi endpoints; curl's -f/--fail-with-body/--max-time/--retry/--retry-connrefused/%header{link}; %{num_retries} is unavailable in 8.5.0; Link pagination function; xargs parallelism and exit code 123; ssh-eats-stdin simulation; mv without -T errors; atomic switch vs delete-then-create (400 requests: 0 vs 132 404s); deploy.sh and the health/backup/deploy of opsctl v0.3; backup rotation, restore drills, lock conflicts, and corruption detection; systemd-analyze calendar; jq examples (Windows jq 1.6 invoked through WSL interop); az cloud list 's JMESPath queries (Azure CLI 2.84.0, not logged in).

Video verification notes

All video links were verified via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) to check titles and channels (2026-11-17):

  • q_juztjhUlA mastering the curl command line - with Daniel Stenberg — Daniel Stenberg
  • I6id1Y0YuNk using curl better - with curl creator Daniel Stenberg — freeCodeCamp Talks
  • w7-St22V1sA Rock-solid curl with Daniel Stenberg — Daniel Stenberg
  • m9dhrq9iRHA The Ultimate JQ Tutorial: Everything You Need to Know to Parse JSON Like a Pro — Earthly
  • OpaiGYxkSuQ Part 1: GNU Parallel script processing and execution — Ole Tange
  • rp7jLi_kgPg Xargs Should Be In Your Command Line Toolbag — DistroTube
  • I4EWvMFj37g Bash in 100 Seconds — Fireship
  • 8ga0xhZuG6k How To Write Bash Scripts In Linux - Complete Guide (Part 17 - Backup Script) — Learn Linux TV
  • n6BuUgkZ5T0 Automate Your Tasks with systemd Timers: A Step-by-Step Guide — Learn Linux TV
  • 7cbP7fzn0D8 Linux Crash Course - Scheduling Tasks with Cron — Learn Linux TV
  • v952m13p-b4 Cron Jobs For Beginners | Linux Task Scheduling — Akamai Developers
  • R8_veQiYBjI GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker — TechWorld with Nana
  • qP8kir2GUgo GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana

No verified video found for: the az / aws --query scripting, and atomic symlink-switch deployment — the corresponding modules provide storyboards instead. Video durations and publish dates were not checked one by one; the cards only describe their general nature.

Audio narration notes

The “Audio” tab uses the browser's built-in Web Speech API (speechSynthesis), preferring zh-CN voices to read the narration script and en-US voices for English terms. This lesson cannot embed MP3 files or generate video; the narration script and storyboard can be handed directly to a TTS / video tool.

Known limitations

  • Content labeled “Expected output (example)” was not run in a real environment; IDs, IPs, accounts, subscriptions, timestamps, and file sizes are all sample values. The cloud CLIs (az / aws after login), GNU parallel, real SSH, and pipelines on GitHub / GitLab were not actually run while writing this.
  • Testing was done on Ubuntu 24.04 (Bash 5.2, curl 8.5.0), not the course baseline Ubuntu 26.04 (Bash 5.3, Rust coreutils); the options used in this lesson exist in both, but please double-check individual uutils behavior differences in your own environment (Lesson 7 tests in CI).
  • During testing, mockapi ran on ports 8765 / 18000, while the course text uniformly uses 8000; the time zone (-0500) in the logs comes from the test machine.
  • “ln -sfn is atomic on its own” depends on the implementation and version; this lesson did not verify it with strace, so the conservative advice is always to use “temp name + mv -T”.
  • The specific Azure CLI exit code values could not be verified in the official documentation, so the text only says “non-zero”. CRON_TZ 's support depends on the cron implementation; see man 5 crontab for details. Pre-installed software on GitHub-hosted runners is defined by the actions/runner-images manifest.
  • opsctl v0.3 builds on the real v0.2.0 code from the combined Lesson 3 and 4 lab: while writing, the code was extracted from the two lesson pages and rebuilt as v0.2.0 in a scratch directory, then this lesson's changes were applied and run end to end (help, health, backup, lock conflict, deploy, rollback, smoke.sh). If Lessons 3 and 4 are changed later, re-verify against their final code.
  • Because util::retry uses full jitter, the “retrying in …s” in the actual output differs each time; PIDs, timestamps, and paths are values from the test environment.