Portability and Production Hardening

Portability and Production Hardening in Bash: --- Before the reform of the armories, a musket was a bespoke object.


The Analogy: Interchangeable Parts at a National Armory

Before the reform of the armories, a musket was a bespoke object. A gunsmith filed each lock, stock and trigger to fit that one weapon, and the parts of no two muskets were the same. When a soldier's musket broke in the field, an armorer could not simply drop in a spare lock; he had to file a new one to fit, by hand, on the spot. The gun worked, beautifully even, but only as the single hand-fitted assembly it was. Nothing about it could be relied upon anywhere else.

The great change was the master gauge. Every part was now made to a single authoritative standard -- a hardened steel gauge kept in the inspection room -- rather than to whatever "looked about right" on one craftsman's bench. A trigger was correct not because it fitted the musket in front of you but because it matched the gauge that every trigger in the country was measured against. That shift from "fits this one" to "matches the standard" is the whole idea of interchangeability, and it is exactly what portability means for a script: correct against the documented standard, not merely against the one shell it happened to be written in.

Two disciplines made the standard real. The first was the go/no-go gauge: an inspector tried each part in a pair of gauges, and a part that would not pass the "go" or that slipped through the "no-go" was rejected before it ever reached assembly. The second was heat treatment -- the parts were hardened by quenching and tempering so they would survive the shock and wear of the field instead of deforming under the first stress. A script is hardened the same way: dependency and precondition checks are its go/no-go gauges, rejecting a bad environment up front, and strict mode, a disciplined field separator and cleanup traps are its heat treatment, so it fails safely under stress rather than corrupting as it goes.

The failure mode is the part that was fitted but never gauged. An armorer in a hurry files a lock until it drops into the musket on his own bench, pronounces it good because "it works on mine," and sends it out -- and it jams in every other weapon it is fitted to, because it was measured against one rifle instead of the standard. A script written to one machine's quirks is that ungauged part: it runs on the author's laptop and fails on the build server, under a different shell, or where the tools are BSD rather than GNU. Portability is the master gauge and hardening is the heat treatment; together they turn a script that works exactly once into one that fits any machine and survives the field.


Syntax or Core Structure

The single most valuable line in a production script is the one that turns the shell's forgiving defaults off. By default bash presses on after a failed command, treats an unset variable as an empty string, and hides failures in the middle of a pipeline. The strict-mode preamble reverses all three, and wrapping the work in a main function keeps the top level clean and gives arguments a name.

#!/usr/bin/env bash
set -euo pipefail

main() {
  local name="${1:-world}"
  printf 'hello, %s
' "$name"
}

main "$@"

Output:

hello, world

The env bash shebang finds bash wherever it lives rather than assuming a fixed path, which is the first portability decision the script makes. set -euo pipefail is the hardening preamble: exit on error, treat unset variables as errors, and fail a pipeline if any stage fails. Inside main, local name="${1:-world}" supplies a default so the script runs with no arguments, and passing "$@" hands the real arguments through. Run with no arguments, the default gives hello, world; the same structure scales up to any real program.


Technical Depth: Hardening Flags and Portable Dependency Checks

Hardening a script is mostly a matter of a few deliberate habits: understanding exactly what each strict-mode flag catches, refusing to run when a required tool is missing, and choosing portable constructs over convenient bashisms. Each of these is a gauge the script applies to its own environment before it does any real work.

Strict Mode, Flag by Flag

The pipefail option is the least obvious of the three and the one that saves the most grief. Without it, a pipeline reports only the exit status of its last command, so a failure in an earlier stage is invisible. The demo drops -e deliberately, so the script survives long enough to print the status; with -e in force the failing pipeline would abort the script before the echo.

#!/usr/bin/env bash
set -uo pipefail

false | true
echo "pipefail rc: $?"

Output:

pipefail rc: 1

The pipeline runs false into true. The last command, true, succeeds, so without pipefail the pipeline's status would be 0 and the failure of false would vanish. With pipefail set, the pipeline takes the status of the rightmost command that failed, so $? is 1 and the problem is visible. In a real script that pipes curl into a parser, this is the difference between noticing that the download failed and silently processing an empty file.

The four elements of a hardening preamble each guard against a different class of silent failure, which is why they are adopted as a set rather than picked individually.

FlagWhat it catchesFailure mode without it
set -e (errexit)Any command that exits non-zeroThe script continues past a failed step as if it had worked
set -u (nounset)Expanding an unset variableA misspelled name becomes empty and mangles a path or command
set -o pipefailA non-zero exit anywhere in a pipelineAn early failure is masked by a successful final stage
IFS of newline and tabField-splitting on spaces within dataA value containing a space is split into two separate arguments

Checking Dependencies Before Using Them

A hardened script does not assume its tools are present; it gauges the environment first and refuses to start if something it needs is absent. The portable way to ask "does this command exist?" is command -v, which is built into every POSIX shell -- unlike which, an external program that is missing on some systems and behaves differently on others.

#!/usr/bin/env bash
set -uo pipefail

need() {
  command -v "$1" >/dev/null 2>&1 || { printf 'missing: %s
' "$1"; return 1; }
}

need printf && echo "printf ok"
need frobnicate || echo "frobnicate absent"

Output:

printf ok
missing: frobnicate
frobnicate absent

The need helper redirects both output streams to /dev/null so only its exit status matters, and prints a diagnostic when the tool is absent. Because printf is a shell builtin it is always found, so the first line prints printf ok. The invented command frobnicate is not found, so need reports it missing and returns non-zero, and the || branch then prints frobnicate absent. In a real preamble you would call need for each required tool and exit once rather than continue, turning a confusing mid-run failure into a clear up-front message.

Portability is the other half of hardening: a script is only correct if it is correct on the machines it will actually run on, not just the author's.

ConcernPortable choiceReason
Conditional testsThe POSIX single-bracket testDouble-bracket tests are a bash extension missing from plain sh
Interpreterenv bash in the shebangThe bash binary sits in different directories across systems
Checking for a toolcommand -vThe which command is non-standard and varies between systems
Numeric workPOSIX arithmetic expansionBash-only constructs fail under a stricter shell such as dash

Real World Example: A Hardened Script With Dependency Checks and Cleanup

The script below pulls the whole topic together. It opens with the hardening preamble, gauges its two dependencies with need, creates a temporary work file, and registers a trap so the temporary file is removed however the script exits -- success, error, or interrupt. It then writes three unsorted lines, counts them, and prints them sorted. Every risky step is guarded, and the one resource it allocates is guaranteed to be cleaned up.

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

need() {
  command -v "$1" >/dev/null 2>&1 || { printf 'missing dependency: %s\n' "$1" >&2; exit 127; }
}

need sort
need wc

work="$(mktemp)"
trap 'rm -f "$work"' EXIT

printf '%s\n' "banana" "apple" "cherry" > "$work"
count="$(wc -l < "$work" | tr -d ' ')"

echo "wrote $count lines to a temp file"
echo "sorted:"
sort "$work"

With sort and wc both present, the script produces the same five lines on every run, and the temporary file never survives it:

Output:

wrote 3 lines to a temp file
sorted:
apple
banana
cherry

The script gauges its environment before doing any work: need sort and need wc exit immediately with a clear message if either tool is missing, so it never fails halfway through with a cryptic error. It then allocates exactly one resource -- the temporary file from mktemp -- and registers cleanup for it in the same breath with trap 'rm -f "$work"' EXIT. Because the trap fires on the EXIT pseudo-signal, the file is removed whether the script finishes normally, aborts under set -e, or is interrupted, so the run leaves nothing behind.

The headline flaw is that this cleanup does not compose. A trap on a given signal holds exactly one command list, and a second trap ... EXIT registered later does not add to the first -- it silently replaces it. The moment a maintainer allocates a second temporary file and, reasonably enough, adds its own trap 'rm -f "$other"' EXIT, the original trap is discarded and the first file is never cleaned up. Tested directly, the first temp file survives the run while only the second is removed. The pattern shown works precisely because there is exactly one trap; it quietly breaks the day someone adds a second, which is the worst kind of flaw -- invisible until the script is extended.

Three narrower limits remain. A hard kill with kill -9 sends SIGKILL, which cannot be trapped, so a script killed that way leaks its temporary file no matter how careful the trap is -- cleanup is best-effort, not a guarantee. The dependency check proves only that a name resolves, not that it is the implementation you assumed: need sort is satisfied equally by GNU sort and BSD sort, whose options differ, so a script can pass its gauge and still behave differently across systems. And the IFS hardening and the quoting of "$work" are overlapping nets rather than independent ones -- with both in place either alone would handle most cases, so the protection is belt-and-braces, and dropping one "because the other covers it" is how spaces-in-filenames bugs quietly return.


Common Mistakes

  1. Shipping with the shell's forgiving defaults. Without strict mode a failed command is ignored, an unset variable expands to an empty string, and a pipeline failure disappears behind a successful last stage. Begin every production script with set -euo pipefail so these become loud errors instead of silent corruption.
  1. Assuming required tools are present. Calling jq or curl without checking means a missing dependency surfaces as a confusing error deep in the run. Gauge every external tool up front with command -v and exit with a clear message naming what is missing.
  1. Using which to test for a command. which is an external program that is absent on some systems and reports success differently on others. Use command -v, which is a POSIX shell builtin and behaves consistently everywhere.
  1. Hard-coding the interpreter path in the shebang. Writing #!/bin/bash breaks on systems where bash lives elsewhere, such as under /usr/local/bin. Use #!/usr/bin/env bash so the interpreter is found on the PATH.
  1. Leaving IFS at its default around untrusted data. The default field separator splits on spaces, so a filename or value containing a space becomes two arguments. Set IFS to newline and tab for data processing, and quote every expansion regardless.
  1. Assuming a second EXIT trap adds to the first. A trap on a signal holds one command list, and registering another for the same signal replaces it rather than appending. Two independent cleanups written the obvious way leak the first resource; use a single trap that tears everything down, or a cleanup function the trap calls.
  1. Treating a trap as a cleanup guarantee. SIGKILL cannot be trapped and a sudden power loss runs nothing, so an EXIT trap is best-effort, not a promise. Design so a leaked temporary file is survivable -- keep them under one dedicated directory that a periodic sweep can clear.
  1. Depending on GNU-only options. Reaching for flags that exist in GNU coreutils but not the BSD tools on macOS means the script works for you and fails for a colleague. Stick to POSIX-specified options, or detect the tool variant and branch.
  1. Using bash extensions under a #!/bin/sh shebang. Constructs like the double-bracket test are bash features; a script that declares sh but uses them breaks under a strict /bin/sh such as dash. Match the constructs you use to the interpreter you declare.

Best Practices

  • Open every production script with a hardening preamble. Use set -euo pipefail and set a deliberate IFS of newline and tab, so failures abort loudly, unset variables are caught, and data is not split on spaces.
  • Gauge dependencies before doing any work. Check each required tool with command -v at the top and exit early with a message naming what is missing, turning a confusing mid-run failure into a clear refusal to start.
  • Prefer portable constructs to convenient bashisms. An env bash shebang, POSIX tests, command -v, and POSIX arithmetic keep the script correct on machines other than your own, which is the whole point of hardening it.
  • Register cleanup with a single trap. Use one EXIT trap that tears down everything, or have it call a cleanup function, so adding a second resource later cannot silently discard the earlier cleanup.
  • Quote every expansion, always. Write "$var" and "$@" even when a value looks safe, and treat the hardened IFS as a backstop rather than a licence to leave expansions unquoted.
  • Fail early and explicitly. Validate inputs and preconditions at the top of the script and exit with a distinct non-zero status on failure, so problems surface before any irreversible work begins.
  • Keep temporary files under control. Create them with mktemp, prefer a single dedicated directory a sweep can clear, and design as though the cleanup trap might not fire, because a hard kill or power loss will skip it.
  • Test in the target shell and toolset. Run the script under the interpreter and tools it will actually meet -- another distribution, macOS with BSD tools, or dash as /bin/sh -- rather than trusting that "works on my machine" means works anywhere.

Practice Exercises

  1. Demonstrate each strict-mode flag. Write a short script that begins with set -euo pipefail and an IFS of newline and tab, then trigger each guard in turn: a failing command that aborts the script, a reference to an unset variable that errors, and a pipeline whose early stage fails. Confirm the behaviour changes when you remove the corresponding flag.
  1. Build a dependency gate. Write a need helper on top of command -v and call it for a list of required tools that includes one deliberately absent name. Show that the script exits at the top with a clear message and a non-zero status, rather than failing partway through its real work.
  1. Make cleanup compose. Start from the hardened example, add a second temporary file with its own trap ... EXIT, and demonstrate that the first file now leaks because the second trap replaced the first. Then fix it with a single trap or a cleanup function and prove that both files are removed on every exit path.
  1. Find and fix the portability breaks. Take a script that uses which, a hard-coded #!/bin/bash, a double-bracket test, and a GNU-only command option, and rewrite each to a portable equivalent. Run the original and the rewrite under dash as /bin/sh and explain which changes were necessary and why.