Courses / Cloud and DevOps Interview Prep / Chapter 3
Module 2 · Linux, scripts and Git · Chapter 3 of 13
Scripts and Git for Safe Change
No prerequisites. Next up: CI/CD Pipelines: Verify, Release Gradually, Roll Back.
Part 1 · Bash that fails loudly
Why scripts fail quietly
Deploy scripts, backup jobs and clean-up tasks are usually Bash, and Bash's defaults are forgiving in the wrong way. A script that hits an error simply carries on to the next line, often with a wrong value in a variable.
Consider rm -rf $DIR/* where $DIR was never set. Bash expands the unset variable to nothing and the command becomes rm -rf /*. Nothing about the script told you the variable was missing. Making failures loud turns that silent disaster into an error message and a stopped script.
Three options, usually written set -euo pipefail near the top, change the defaults. -e makes the shell exit when a command fails. -u makes an unset variable an error. -o pipefail makes a pipeline fail when any command in it fails, not only the last one. A fourth habit is not an option: quote every expansion, so a value with spaces or a * stays one word.
Without quotes, Bash performs word splitting (breaking a value at spaces) and globbing (expanding * and ? into file names) on the result of every expansion. A file called my report.txt becomes two arguments, and * becomes a list of whatever is in the directory.
What each option does, run for real
Each case below runs in its own bash -c so the options do not leak between them. Read the exit status as well as the output: a script that exits 0 after a failure is the problem.
$ bash -c 'false; echo still running' still running exit status 0 $ bash -c 'set -e; false; echo still running' exit status 1 $ bash -c 'set -e; false || echo handled; echo still running' handled still running exit status 0 $ bash -c 'set -e; if false; then :; fi; echo still running' still running exit status 0 $ bash -c 'set -e; false | cat; echo still running' still running exit status 0 $ bash -c 'set -eo pipefail; false | cat; echo still running' exit status 1
Output from one run.
The second case stops at false and exits 1, which is -e working. The third shows the first exception: a failure on the left of || or && is treated as handled. The fourth shows another: the condition of an if is allowed to fail. The manual lists these exceptions, and they are the reason -e alone is not a safety net.
The fifth and sixth cases show why -o pipefail is needed. In false | cat, the pipeline's status is the status of the last command, cat, which succeeds, so -e never fires. With pipefail the pipeline reports the failure and the script stops.
Unset variables and traps
$ bash -c 'set -u; echo "dir is $DIR"' bash: line 1: DIR: unbound variable exit status 127 $ bash -c 'set -u; echo "dir is ${DIR:-/tmp}"' dir is /tmp exit status 0 $ bash -c 'set -e; f() { false; echo in f; }; f || :; echo done' in f done exit status 0 $ bash -c 'set -e; x=$(false); echo "x is empty, still running"' exit status 1 $ bash -c 'set -e; g() { local x=$(false); echo masked; }; g' masked exit status 0
-u turns the unset $DIR into an error, and the default form ${DIR:-/tmp} is the way to say "use /tmp when it is unset" on purpose. The unbound-variable error exits with status 127 in this shell, so do not depend on the number.
The last three cases are the traps. A function called on the left of || runs with -e switched off, so in f is printed even though false came first. The same holds inside an if condition. A failed command substitution in a plain assignment, x=$(false), does stop the script. But local x=$(false) reports the status of local, which succeeds, so the failure is hidden. Declare first and assign on the next line.
A trap runs a command when the shell receives a signal or exits. trap COMMAND EXIT runs whenever the shell exits, normally or through an error under -e. The one exit it cannot catch is SIGKILL, after which nothing runs. It is the place to delete temporary files:
#!/usr/bin/env bash set -euo pipefail tmp=$(mktemp -d) trap 'echo "cleanup: removing the temp dir"; rm -rf "$tmp"' EXIT echo "working in a temp dir" false echo "never printed"
trapdemo.sh
$ ./trapdemo.sh; echo "exit status $?" working in a temp dir cleanup: removing the temp dir exit status 1
Output from one run. The clean-up ran although the script failed.
Linting with ShellCheck
ShellCheck is an open-source static analyser for shell scripts. It reads a script without running it and reports the quoting and logic mistakes above, each with a code such as SC2086. Here is a clean-up script that keeps the newest three release folders, written the quick way:
#!/bin/bash # prune old release folders RELEASES=$1 cd $RELEASES for d in $(ls -t | tail -n +4); do rm -rf $d done echo pruned in $RELEASES
old.sh
$ shellcheck --version | sed -n 2p version: 0.11.0 $ shellcheck -f gcc old.sh # message text cut, code kept old.sh:4:1: warning SC2164 old.sh:4:4: note SC2086 old.sh:5:12: note SC2012 old.sh:6:10: note SC2086 old.sh:8:16: note SC2086 exit status 1
Output from one run; the command keeps the position and the code and drops the message text.
Five findings. SC2164 says cd can fail and the script would go on in the wrong directory. SC2086 appears three times, once for each unquoted expansion. SC2012 says to avoid parsing ls output, which breaks on odd file names. The ShellCheck wiki page for each code explains the fix. The rewrite below applies set -euo pipefail, quotes everything, checks its argument and cleans up with a trap.
#!/usr/bin/env bash # Prune release folders, keeping the newest three. set -euo pipefail releases=${1:?usage: prune.sh RELEASES_DIR} cd -- "$releases" tmp=$(mktemp) trap 'rm -f "$tmp"' EXIT ls -t > "$tmp" tail -n +4 "$tmp" | while IFS= read -r d; do rm -rf -- "$d" done echo "pruned in $releases"
new.sh
$ shellcheck -f gcc new.sh
exit status 0One finding was silenced rather than fixed. The new script still reads the output of ls -t, now through a file, so ShellCheck no longer sees the pattern it warns about. That is acceptable here only because the release script itself creates these folders with plain names such as r5; for names you do not control, a file name with a newline in it would still split into two entries. A clean lint result is evidence, not proof.
ShellCheck is quiet on the new script. Run on a real release folder, it keeps the three newest and removes the rest, and it stops with a message when the folder or the argument is wrong:
$ ls -t /tmp/rel | tr "\n" " " r5 r4 r3 r2 r1 $ ./new.sh /tmp/rel pruned in /tmp/rel $ ls -t /tmp/rel | tr "\n" " " r5 r4 r3 $ ./new.sh /tmp/does-not-exist new.sh: line 6: cd: /tmp/does-not-exist: No such file or directory exit status 1 $ ./new.sh new.sh: line 5: 1: usage: prune.sh RELEASES_DIR exit status 1
Output from one run.
Check yourself
Why does set -e not stop the script at false | cat?
- A pipeline's status is the status of its last command, and
catsucceeds. Add-o pipefailso the failure of any stage fails the pipeline.
local x=$(some_command) hides a failure of some_command. Why?
- The status of the line is the status of
local, which succeeds. Declare withlocal xfirst and assign on a separate line.
What does trap 'rm -rf "$tmp"' EXIT give you that a rm at the end of the script does not?
- It runs on every exit path, including an error that stops the script early.
Part 2 · Scripts safe to run twice
Idempotent by design
Scripts get run twice. A deploy fails halfway and someone reruns it; a scheduler retries a task that timed out; two people run the same fix. A script is idempotent when running it again leaves the system in the same state as running it once.
The usual way to get there is to check before you change. "Create the folder" becomes "create the folder unless it exists". "Point the link at release 42" becomes "point the link at release 42 unless it already does". The script prints what it found and what it did, so a rerun that did nothing says so.
A second habit is atomic change: either the whole step happened or none of it. If a script unpacks an archive straight into the final folder and crashes halfway, the folder exists but is half full, and the next run, seeing the folder, skips the step. Unpack into a temporary name, then rename it into place. A rename inside one file system happens in one step, so other programs see the old state or the new state and nothing in between.
The third habit is a dry run: a flag that prints each change instead of making it. Reviewers can read the plan before anything happens, and the script has to describe what it would do, which exposes surprises early.
A release script in Bash
The task: unpack a build artifact into a release folder and point a current link at it. The run function is the whole dry-run mechanism: it either prints the command or executes it. Every change goes through it.
#!/usr/bin/env bash # Unpack an artifact and point "current" at it. Safe to run twice. set -euo pipefail dry=0 if [[ ${1:-} == --dry-run ]]; then dry=1; shift; fi artifact=${1:?usage: release.sh [--dry-run] ARTIFACT.tgz ROOT} root=${2:?usage: release.sh [--dry-run] ARTIFACT.tgz ROOT} id=$(basename "$artifact" .tgz) rel="$root/releases/$id" run() { if ((dry)); then echo "would run: $*"; else "$@"; fi; } if [[ -d $rel ]]; then echo "release $id is already unpacked" else run rm -rf "$rel.tmp" run mkdir -p "$rel.tmp" run tar -xzf "$artifact" -C "$rel.tmp" run mv "$rel.tmp" "$rel" fi if [[ $(readlink "$root/current" || true) == "releases/$id" ]]; then echo "current already points at $id" else run ln -sfn "releases/$id" "$root/current" fi
release.sh
The lab builds a small artifact and runs the script three ways: a dry run, the real run, and a second real run.
$ ./release.sh --dry-run build-42.tgz /tmp/app would run: rm -rf /tmp/app/releases/build-42.tmp would run: mkdir -p /tmp/app/releases/build-42.tmp would run: tar -xzf build-42.tgz -C /tmp/app/releases/build-42.tmp would run: mv /tmp/app/releases/build-42.tmp /tmp/app/releases/build-42 would run: ln -sfn releases/build-42 /tmp/app/current $ ls /tmp/app/releases $ ./release.sh build-42.tgz /tmp/app $ readlink /tmp/app/current; cat /tmp/app/current/VERSION releases/build-42 version 42 $ ./release.sh build-42.tgz /tmp/app # again release build-42 is already unpacked current already points at build-42
Output from one run. Nothing was created by the dry run.
The dry run lists five commands and leaves the releases folder empty, which ls confirms. The real run prints nothing because every step succeeded quietly. The second real run reports both checks as already satisfied and changes nothing.
Is the link swap itself atomic? POSIX describes ln -f as removing the old link and then creating the new one, which leaves an instant with no link. GNU ln (coreutils, version 9.4 here) does better: its source creates the new link under a random temporary name and renames it over the old one. The script below checks this on this machine by swapping a link thousands of times while a reader keeps calling readlink.
The same task in Python
Past about fifty lines, or when you need real data structures, a script is usually better in Python. The task is the same; the standard library gives argparse for options, pathlib for paths and subprocess for running other programs. subprocess.run(..., check=True) raises an error when the command fails, which is Python's version of set -e.
"""Unpack an artifact and point "current" at it. Safe to run twice.""" import argparse import shutil import subprocess from pathlib import Path ap = argparse.ArgumentParser() ap.add_argument("--dry-run", action="store_true") ap.add_argument("artifact", type=Path) ap.add_argument("root", type=Path) args = ap.parse_args() rel_id = args.artifact.name.removesuffix(".tgz") rel = args.root / "releases" / rel_id tmp = rel.with_name(rel_id + ".tmp") current = args.root / "current" target = Path("releases", rel_id) def step(text, action): print(("would: " if args.dry_run else "") + text) if not args.dry_run: action()
release.py, part 1
if rel.is_dir(): print(f"release {rel_id} is already unpacked") else: step("unpack to a temporary folder", lambda: ( shutil.rmtree(tmp, ignore_errors=True), tmp.mkdir(parents=True), subprocess.run( ["tar", "-xzf", args.artifact, "-C", tmp], check=True))) step("rename it into place", lambda: tmp.rename(rel)) if current.is_symlink() and current.readlink() == target: print(f"current already points at {rel_id}") else: step(f"point current at {rel_id}", lambda: ( current.unlink(missing_ok=True), current.symlink_to(target)))
release.py, part 2
The step helper plays the part of run: it prints what it will do, and does it only when --dry-run is absent. The script is run with uv run --python 3.12, which finds or fetches the right interpreter and needs no virtual environment for a script without dependencies. One difference from the Bash version: unlink followed by symlink_to leaves a moment with no link, so a version for a busy server would create the link under a temporary name and call os.replace to rename it into place.
$ uv run --python 3.12 release.py --dry-run build-42.tgz /tmp/app2 would: unpack to a temporary folder would: rename it into place would: point current at build-42 $ uv run --python 3.12 release.py build-42.tgz /tmp/app2 unpack to a temporary folder rename it into place point current at build-42 $ uv run --python 3.12 release.py build-42.tgz /tmp/app2 # again release build-42 is already unpacked current already points at build-42 $ readlink /tmp/app2/current releases/build-42
Output from one run.
Retries with backoff and jitter
Some failures are temporary: a service that is still starting, a network blip. A retry loop handles them, and a careless one makes things worse. If every client retries after exactly one second, they all arrive together and overload the service again.
Exponential backoff doubles the wait after each failure: 0.4, 0.8, 1.6 seconds. Jitter randomises each wait, so clients spread out. "Full jitter" picks a random delay between zero and the backoff value. A cap stops the delays growing without limit, and a maximum attempt count stops a permanent fault from retrying forever.
"""Run a command up to N times: exponential backoff with full jitter.""" import random import subprocess import sys import time random.seed(7) # so the lab prints the same delays every run BASE, CAP, TRIES = 0.2, 2.0, 5 for attempt in range(1, TRIES + 1): result = subprocess.run(sys.argv[1:]) if result.returncode == 0: print(f"attempt {attempt}: ok") break code = result.returncode if attempt == TRIES: sys.exit(f"attempt {attempt}: exit {code}, giving up") delay = random.uniform(0, min(CAP, BASE * 2 ** attempt)) print(f"attempt {attempt}: exit {code}, wait {delay:.2f}s") time.sleep(delay)
retry.py
The helper script flaky.sh fails twice and then succeeds. The random generator is seeded so the lab prints the same delays each time; in production you would not seed it.
$ uv run --python 3.12 retry.py bash flaky.sh attempt 1: exit 1, wait 0.13s attempt 2: exit 1, wait 0.12s attempt 3: ok
Output from one run. Each wait is random, below that attempt's backoff value.
A command that never succeeds shows the other end. After the fifth attempt the script stops without a last pointless wait and exits non-zero, so whatever called it sees the failure.
$ uv run --python 3.12 retry.py false; echo "exit status $?" attempt 1: exit 1, wait 0.13s attempt 2: exit 1, wait 0.12s attempt 3: exit 1, wait 1.04s attempt 4: exit 1, wait 0.14s attempt 5: exit 1, giving up exit status 1
Output from one run.
Retry only operations that are safe to repeat. That brings the lesson back to the start: an idempotent step can be retried freely, and a non-idempotent one needs a guard first.
Why unpack into a temporary folder and rename, instead of unpacking in place?
Part 3 · Git habits for safe change
Small, reviewed, reversible
Version control is the safety net for every change, in code and in infrastructure files alike. Used well, it makes a mistake cheap to find and cheap to undo.
Keep commits small and each one coherent: one change, one reason, a message that says why. A small commit is easy to review, and when it turns out to be the bad one, easy to remove. Work on a branch and merge through a review, so a second person reads the change before it reaches the shared line.
Teams enforce this with protected branches. In GitHub the available rules include requiring pull request reviews, requiring status checks to pass, requiring conversation resolution, requiring signed commits, requiring linear history and requiring a merge queue. Force pushes and deletions of a protected branch are blocked by default. These rules are settings on the server, so they hold even when someone forgets the habit.
Treat history that others have pulled as read-only. Rewriting it forces everyone else to repair their copies. That rule decides which undo command to use.
Revert or reset
git revert records a new commit that undoes an earlier one. History stays intact, so it is safe for commits that others already have. git reset moves a branch pointer back, which drops commits from the branch. It suits commits that exist only on your machine.
The throwaway repository in the lab has three commits, the last of which turns retries off. It is already pushed to a shared remote, so the right undo is a revert.
$ git log --oneline <id> Turn retries off <id> Add timeout <id> Add retry setting $ git revert --no-edit HEAD [main <id>] Revert "Turn retries off" $ git log --oneline <id> Revert "Turn retries off" <id> Turn retries off <id> Add timeout <id> Add retry setting $ git push origin main # shared history stays intact <id>..<id> main -> main
Output from one run. Commit ids are replaced by <id>.
The log now has four entries: the bad commit stays, and a commit that undoes it sits on top. The push is an ordinary fast-forward, so teammates simply pull. For a commit that was never shared, reset is fine. Below, a local commit "Add debug flag", never pushed, is dropped with reset --hard, and the reflog (git's record of where HEAD has been) shows how to get back if that was a mistake.
$ git reset --hard HEAD~1 HEAD is now at <id> Revert "Turn retries off" $ git reflog -3 <id> HEAD@{0}: reset: moving to HEAD~1 <id> HEAD@{1}: commit: Add debug flag <id> HEAD@{2}: revert: Revert "Turn retries off"
The reflog keeps the dropped commit reachable for a while.
git revert of a merge commit needs -m 1 to say which parent is the mainline. The manual warns that reverting a merge also tells Git you never want those changes, which complicates merging the same branch again.
Force-pushing without losing a colleague's work
Sometimes you do rewrite published history, for example after amending a commit on your own feature branch. The push is then refused as a non-fast-forward and you must force it. Plain --force overwrites whatever the remote has. --force-with-lease overwrites only if the remote branch is still where your last fetch saw it.
In the lab, Asha pushes a commit. Dev Nair pulls it, adds a commit and pushes. Asha, who has not fetched, amends her commit message and pushes with a lease.
$ git push --force-with-lease origin main To <remote> ! [rejected] main -> main (stale info) $ git fetch origin; git log --oneline origin/main <id> Add timeout <id> Add retry setting
Output from one run.
The push is rejected with stale info: the remote moved after her last fetch, so the lease no longer holds. After the fetch she sees Dev's commit. Had she used plain --force instead, the result is below.
$ git push --force origin main To <remote> + <id>...<id> main -> main (forced update) $ git log --oneline origin/main # what the remote holds now <id> Add retry setting for orders
The forced push succeeded and the remote now holds only her amended commit. Dev's "Add timeout" commit is gone from the branch. It still exists in Dev's clone, but it no longer exists on the shared branch.
The Git manual adds a caution: --force-with-lease without an explicit expected value can be fooled by a background git fetch, which updates your remote-tracking branch without you reading the new commits. --force-if-includes guards against that case. The habit that always works is to fetch, read what arrived, and only then push.
When is git revert the right undo, and when is git reset?
- Revert for commits others already have: it adds a new commit and rewrites nothing. Reset for commits only you have, because it removes them from the branch.
Why did --force-with-lease reject the push in the lab?
Part 4 · Finding the commit that broke it
Binary search over history
A test passed last month and fails now, and sixteen commits sit between the two. Reading all of them is slow. Bisection finds the first bad commit by binary search: test the commit in the middle, discard the half that cannot contain the culprit, repeat. Sixteen candidates need at most four tests, and a thousand need about ten.
git bisect automates the walk. You give it one commit known to be bad and one known to be good. Git checks out the middle commit and waits for your verdict, or runs a script that gives the verdict for you. The result is the first commit where the test turns bad.
git bisect run SCRIPT reads the script's exit status. 0 means the commit is good. 1 to 127 except 125 means bad. 125 means the commit cannot be tested at all, so skip it. Any other value, such as 128 and above, aborts the bisection. The reason for 125 is that shells reserve 126 and 127 for "not executable" and "not found".
For this to work the test must be deterministic and fast, and it must exit with the right code. A script that passes or fails at random sends bisection down the wrong half, and nothing flags the mistake.
Sixteen commits, four tests
The lab repository has sixteen commits, each appending one line to a file. Commit 11, "Change pool size", appends the word BUG. The test script exits 1 if the file contains BUG and 0 if not. Bisection starts with the newest commit as bad and the oldest as good.
Watch for the range of suspect commits halving after every test
Read it as steps
Four tests find the first bad commit among sixteen.
The scene matches the run below: the four tests were c8, c12, c10 and c11, in that order. The pointers lo and hi close in until they are neighbours, and the commit at hi is the answer.
Running bisect run
The commands are two lines. The first marks the ends of the range, the second hands over the test script. The script lives outside the repository, so checking out an old commit does not remove it.
$ git log --oneline | wc -l 16 $ git bisect start HEAD HEAD~15 Bisecting: 7 revisions left to test after this (roughly 3 steps) [<id>] Add cache layer $ git bisect run ../check.sh check: ok Bisecting: 3 revisions left to test after this (roughly 2 steps) [<id>] Add batch endpoint check: bug present Bisecting: 1 revision left to test after this (roughly 1 step) [<id>] Add rate limit check: ok Bisecting: 0 revisions left to test after this (roughly 0 steps) [<id>] Change pool size check: bug present <id> is the first bad commit commit <id> Author: Asha Rao <asha@example.com> Date: Sun Nov 22 13:40:41 2026 +0000 Change pool size app.txt | 1 + 1 file changed, 1 insertion(+) bisect found first bad commit
Output from one run. Commit ids and dates differ each run.
Each "Bisecting" line reports how many commits are left to test. The four check: lines are the four test runs. The result names the commit, its author and its message, and the test script never ran twice on the same commit.
Afterwards git bisect reset returns the repository to the branch you started on. Forgetting this leaves you on a detached commit in the middle of history.
Commits that cannot be tested
Real history contains commits that do not build, perhaps because an interface changed and a fix came in the next commit. Testing such a commit gives a failure that says nothing about the bug. The exit code 125 tells bisect to skip that commit and pick a neighbour.
The lab repeats the run with commit 8 marked as unbuildable, which is the commit bisect would have tested first. The test script exits 125 when a marker file is present.
$ git bisect start HEAD HEAD~15 Bisecting: 7 revisions left to test after this (roughly 3 steps) [<id>] Add cache layer $ git bisect run ../check.sh Bisecting: 6 revisions left to test after this (roughly 3 steps) [<id>] Fix typo check: ok Bisecting: 2 revisions left to test after this (roughly 2 steps) [<id>] Update docs check: bug present Bisecting: 1 revision left to test after this (roughly 1 step) [<id>] Change pool size check: bug present Bisecting: 0 revisions left to test after this (roughly 0 steps) [<id>] Add rate limit check: ok <id> is the first bad commit commit <id> Author: Asha Rao <asha@example.com> Date: Sun Nov 22 13:40:42 2026 +0000 Change pool size app.txt | 1 + 1 file changed, 1 insertion(+) bisect found first bad commit
Output from one run. The skipped commit prints no check line.
The skipped commit left no check: line, and bisect moved to a nearby commit. The search took a different path and needed an extra step, yet it arrived at the same first bad commit, "Change pool size". If the skipped commits had been next to the culprit, git would instead list the several candidates it cannot tell apart.
Bisect pays off most when commits are small and the suite is fast. That is another reason for the habits of the previous lesson.
Why does git bisect run need a script exit code of 125 in some cases?
- Exit 125 means "this commit cannot be tested", so bisect skips it. Reporting it as bad would mislead the search.
How many tests does bisection need for 16 commits?
- At most four, and the lab run used four. Each test halves the remaining range.
Part 5 · Checks before the push
Catch it on your machine
A mistake caught while you are still typing costs seconds. The same mistake caught in a review costs a day, and in production it costs an incident. Git hooks are scripts that Git runs at set points; the pre-commit hook runs just before a commit is recorded and can refuse it.
The pre-commit tool manages those hooks. You list hooks in .pre-commit-config.yaml at the project root, and pre-commit install writes a Git hook that runs them on every git commit. During a commit the hooks see only the staged contents of files, and pre-commit sets aside unstaged changes so they do not skew the result.
Good hooks are fast and have few false alarms. Typical ones: a shell linter, a YAML linter, a formatter and a secrets scanner. A slow hook makes people skip hooks, and --no-verify skips all of them in one go, which is why checks that must hold also run in CI.
Three hooks in a throwaway repo
The lab uses three tools: ShellCheck for scripts, yamllint for YAML and detect-secrets, which looks for strings shaped like credentials. All three are installed from PyPI. The configuration declares them as repo: local hooks that run programs already installed. The pre-commit documentation notes that language: system has been renamed unsupported, and this config uses the new name.
repos:
- repo: local
hooks:
- id: shellcheck
name: shellcheck
entry: shellcheck
language: unsupported
types: [shell]
- id: yamllint
name: yamllint
entry: yamllint -d relaxed
language: unsupported
types: [yaml]
- id: detect-secrets
name: detect-secrets
entry: detect-secrets-hook --baseline .secrets.baseline
language: unsupported.pre-commit-config.yaml
The first commit adds a script with an unquoted rm -rf $1/*, a YAML file with a duplicate key and a settings file holding the AWS documentation's example access key. All three are made-up test data, and the key is a published example that grants nothing.
$ pre-commit install pre-commit installed at .git/hooks/pre-commit $ git commit -m "Add cleanup script" shellcheck ... Failed - hook id: shellcheck - exit code: 1 In clean.sh line 2: rm -rf $1/* ^--^ SC2115 (warning): Use "${var:?}" to ensure this never expands to /* . ^-- SC2086 (info): Double quote to prevent globbing and word splitting. Did you mean: rm -rf "$1"/* yamllint ... Failed - hook id: yamllint - exit code: 1 ci.yml 4:1 error duplication of key "jobs" in mapping (key-duplicates) detect-secrets ... Failed - hook id: detect-secrets - exit code: 1 ERROR: Potential secrets about to be committed to git repo! Secret Type: AWS Access Key Location: settings.py:1 exit status 1
Output from one run; long lines are wrapped and the help text is cut.
Fixing and committing
Each hook names the file and the line. ShellCheck reports SC2115 and SC2086 and suggests the quoted form. yamllint reports the duplicate key at line 4. detect-secrets names the type, AWS Access Key, and the location. The commit did not happen, and exit status 1 is what Git sees.
The fixes: quote the argument and fail if it is empty, remove the duplicate key, and read the key from the environment instead of writing it in code. Staging the fixed files and committing again runs the hooks again.
$ git commit -m "Add cleanup script" # after the fixes shellcheck ... Passed yamllint ... Passed detect-secrets ... Passed [main <id>] Add cleanup script 3 files changed, 7 insertions(+) create mode 100644 ci.yml create mode 100644 clean.sh create mode 100644 settings.py
The same commit after the fixes.
All three hooks pass and the commit is recorded. A scanner can only match patterns, so a secret that looks like nothing in particular slips through. Treat it as a net for common mistakes, and rotate any real key that reaches a commit, since history keeps it.
What belongs in CI instead
Local hooks are a convenience that each developer can bypass or forget to install. Continuous integration (CI) is the shared check that runs on the server for every change, so it is the place for rules that must hold. The pre-commit documentation suggests pre-commit run --all-files for CI, and --from-ref with --to-ref to check only the changed files.
| Check | Pre-commit hook | CI |
|---|---|---|
| Shell and YAML lint | Yes: fast, files are small | Yes: the same config, as the enforced copy |
| Secrets scan | Yes: stops the secret before it enters history | Yes: catches what a skipped hook missed |
| Unit tests | Only if they take seconds | Yes, always |
| Integration tests, builds | No: too slow | Yes |
Run the same hook configuration in both places, so a pass on your machine predicts a pass in CI.
| Term | Meaning |
|---|---|
| Idempotent | Running a step again leaves the same state as running it once |
| Dry run | A mode that prints the changes a script would make without making them |
| Bisection | Binary search over commits for the first one where a test turns bad |
| Lease | Git's check that a remote branch is still where you last saw it |
All chapters · Previous: Linux and CLI Troubleshooting: Evidence, Isolation and Reversible Fixes