shell-scripting-conventions
Step 6 (code) of the pipeline (WORKFLOW.md), for shell specifically, because shell breaks the
assumption the rest of the pipeline rests on: by default, a shell script that fails still exits 0,
and a gate that exits 0 is a gate that passed.
This block exists because it happened here. The repo's own gate hook parsed its payload with a tool that
wasn't installed, got an empty value, and allowed everything — while its documentation claimed a
malfunctioning hook blocks. It was written to be fail-closed and shipped fail-open.
When
When writing or reviewing: a hooks/ script, a CI step of more than one command, a make target with
logic in it, a deploy or migration script, anything run by a scheduler.
Steps
1. Make failure the default
set -euo pipefail at the top. Exit on error, fail on an unset variable, and propagate a failure
from anywhere in a pipeline instead of only the last command. Two limits of -u: the Bash manual excludes
$@ and $*, and a non-interactive shell exits on the error.
- Know where
-e doesn't save you. Bash does not exit when the failing command is the test of an if,
follows while or until, is in an && or || list anywhere but last, is negated with !, or is in a
pipeline but the last (unless pipefail). A function or compound command run in such a context ignores
-e for its whole body, even if it sets -e itself. Check exit codes explicitly there.
local x=$(cmd) hides the failure of cmd: local returns zero unless misused, so -e never sees it.
Declare first, assign on the next line.
- Quote every expansion:
"$var", "$@", "${arr[@]}". An unquoted empty variable makes an
argument disappear, which turns rm -rf "$dir/"* into something else entirely.
cd is checked: cd "$dir" || exit 1. A failed cd followed by a destructive command is the
classic shell disaster.
2. Fail closed, and only on the path you guard
- Decide the failure posture explicitly and write it in a comment-free, obvious way: a gate that
cannot determine the answer must block, not allow.
- But guard narrowly. Blocking on every unexpected input makes the script unusable and it gets
removed. Fast-path out with a cheap check that needs no parser, and only fail closed once you know the
protected case is in play.
- Never depend on a tool being present without checking.
command -v (zero if found, non-zero if not, per the Bash manual) first, and decide what its
absence means — for a gate it means block, for a convenience it means skip.
- Exit codes are the interface. For hooks, the host's contract defines which code blocks; get it
from the documentation, not from memory (
source-freshness).
3. Portability and provenance
#!/usr/bin/env bash when you use bash features, sh only if the script is genuinely POSIX. A
bashism under #!/bin/sh fails on the machine that has a real sh.
- Windows/WSL crossing: a file written from Windows carries CRLF, and
\r at the end of a shebang
or a variable breaks in ways the error message won't explain. Strip it, and never assume the editor
didn't add it.
- The executable bit is part of the change. A tool rewriting the file can drop it; git tracks it
(
git update-index --chmod=+x sets it, per the git manual), and a script committed 100644 fails on someone else's clone with
"Permission denied" and no other clue.
- Prefer a real language past ~50 lines of logic. Shell has no types, no test framework you'll
actually use, and error handling you have to remember. Parsing structured data is the usual signal.
4. Prove it, because shell has no compiler
- Run
shellcheck on the script before it lands. It catches the quoting and expansion classes above mechanically. If it is not installed, install it from the system package manager; if that is not possible, say so in the report and re-read the script against §1 instead of skipping the step silently.
- Run the failure cases, not just the happy one. Missing tool, unparseable input, absent file, empty
variable. Confirm each one produces the exit code you intended — a fail-open bug is invisible in the
happy path by definition.
- Write the case table down next to the script, with what each case must do. It's the only test suite
a hook is going to get.
- A script that guards something gets its guard tested against a real attempt to slip through, not
only against a well-formed call.
Output / checkpoint
For anything gate-like: the failure posture stated, the narrow guard, and the case table run with its
results. shellcheck clean. The exec bit recorded in git.
Guardrails
- Never let a script exit 0 on a path it didn't handle, and never let a gate degrade to permissive
when a dependency is missing.
- Never
rm -rf a path built from an unquoted or unvalidated variable.
- Never parse structured data with regex in shell when a real interpreter is available.
- Never trust "it worked when I ran it" — you ran the happy path, and the exec bit was set locally.
- Never put a secret in a script, an argument list or an
echo; arguments are visible in the process
list (auth-session-conventions §2.4).
Origin
The defensive baseline (set -euo pipefail, quoting, checked cd, shellcheck) is long-established
public practice and is taken as-is. Everything in §2 and §4 is ours and comes from this repo's own
verify-gate.sh: the fail-open bug caused by assuming a parser was installed, the fix's parser-free fast
path so a machine without it still works normally, the exec bit silently dropped when a tool rewrote the
file, and CRLF from the Windows side corrupting scripts copied into WSL. All four were real, all four
were invisible on the happy path.
1---2name: shell-scripting-conventions3description: Use when writing or reviewing a shell script that anything depends on — a hook, a CI step, a make target, a deploy or maintenance script — where the default behaviour of the shell is to continue after a failure and report success.4metadata:5 source: https://skillmd.com/skills/techmefr/shell-scripting-conventions6---78# shell-scripting-conventions910Step 6 (`code`) of the pipeline (`WORKFLOW.md`), for shell specifically, because shell breaks the11assumption the rest of the pipeline rests on: **by default, a shell script that fails still exits 0**,12and a gate that exits 0 is a gate that passed.1314This block exists because it happened here. The repo's own gate hook parsed its payload with a tool that15wasn't installed, got an empty value, and allowed everything — while its documentation claimed a16malfunctioning hook blocks. It was written to be fail-closed and shipped fail-open.1718## When19When writing or reviewing: a `hooks/` script, a CI step of more than one command, a `make` target with20logic in it, a deploy or migration script, anything run by a scheduler.2122## Steps2324### 1. Make failure the default251. **`set -euo pipefail` at the top.** Exit on error, fail on an unset variable, and propagate a failure26 from anywhere in a pipeline instead of only the last command. Two limits of `-u`: the Bash manual excludes27 `$@` and `$*`, and a non-interactive shell exits on the error.282. **Know where `-e` doesn't save you.** Bash does not exit when the failing command is the test of an `if`,29 follows `while` or `until`, is in an `&&` or `||` list anywhere but last, is negated with `!`, or is in a30 pipeline but the last (unless `pipefail`). A function or compound command run in such a context ignores31 `-e` for its whole body, even if it sets `-e` itself. Check exit codes explicitly there.323. **`local x=$(cmd)` hides the failure of `cmd`:** `local` returns zero unless misused, so `-e` never sees it.33 Declare first, assign on the next line.344. **Quote every expansion**: `"$var"`, `"$@"`, `"${arr[@]}"`. An unquoted empty variable makes an35 argument disappear, which turns `rm -rf "$dir/"*` into something else entirely.365. **`cd` is checked**: `cd "$dir" || exit 1`. A failed `cd` followed by a destructive command is the37 classic shell disaster.3839### 2. Fail closed, and only on the path you guard401. **Decide the failure posture explicitly and write it in a comment-free, obvious way**: a gate that41 cannot determine the answer must **block**, not allow.422. **But guard narrowly.** Blocking on every unexpected input makes the script unusable and it gets43 removed. Fast-path out with a cheap check that needs no parser, and only fail closed once you know the44 protected case is in play.453. **Never depend on a tool being present without checking.** `command -v` (zero if found, non-zero if not, per the Bash manual) first, and decide what its46 absence means — for a gate it means block, for a convenience it means skip.474. **Exit codes are the interface.** For hooks, the host's contract defines which code blocks; get it48 from the documentation, not from memory (`source-freshness`).4950### 3. Portability and provenance511. **`#!/usr/bin/env bash`** when you use bash features, `sh` only if the script is genuinely POSIX. A52 bashism under `#!/bin/sh` fails on the machine that has a real `sh`.532. **Windows/WSL crossing**: a file written from Windows carries CRLF, and `\r` at the end of a shebang54 or a variable breaks in ways the error message won't explain. Strip it, and never assume the editor55 didn't add it.563. **The executable bit is part of the change.** A tool rewriting the file can drop it; git tracks it57 (`git update-index --chmod=+x` sets it, per the git manual), and a script committed 100644 fails on someone else's clone with58 "Permission denied" and no other clue.594. **Prefer a real language past ~50 lines of logic.** Shell has no types, no test framework you'll60 actually use, and error handling you have to remember. Parsing structured data is the usual signal.6162### 4. Prove it, because shell has no compiler631. **Run `shellcheck` on the script before it lands.** It catches the quoting and expansion classes above mechanically. If it is not installed, install it from the system package manager; if that is not possible, say so in the report and re-read the script against §1 instead of skipping the step silently.642. **Run the failure cases, not just the happy one.** Missing tool, unparseable input, absent file, empty65 variable. Confirm each one produces the exit code you intended — a fail-open bug is invisible in the66 happy path by definition.673. **Write the case table down** next to the script, with what each case must do. It's the only test suite68 a hook is going to get.694. **A script that guards something gets its guard tested against a real attempt to slip through**, not70 only against a well-formed call.7172## Output / checkpoint73For anything gate-like: the failure posture stated, the narrow guard, and the case table run with its74results. `shellcheck` clean. The exec bit recorded in git.7576## Guardrails77- **Never let a script exit 0 on a path it didn't handle**, and never let a gate degrade to permissive78 when a dependency is missing.79- **Never `rm -rf` a path built from an unquoted or unvalidated variable.**80- Never parse structured data with regex in shell when a real interpreter is available.81- **Never trust "it worked when I ran it"** — you ran the happy path, and the exec bit was set locally.82- Never put a secret in a script, an argument list or an `echo`; arguments are visible in the process83 list (`auth-session-conventions` §2.4).8485## Origin86The defensive baseline (`set -euo pipefail`, quoting, checked `cd`, `shellcheck`) is long-established87public practice and is taken as-is. Everything in §2 and §4 is ours and comes from this repo's own88`verify-gate.sh`: the fail-open bug caused by assuming a parser was installed, the fix's parser-free fast89path so a machine without it still works normally, the exec bit silently dropped when a tool rewrote the90file, and CRLF from the Windows side corrupting scripts copied into WSL. All four were real, all four91were invisible on the happy path.