Portable CI Scripts and Exit Discipline

Portable CI Scripts and Exit Discipline in Bash: A merchant ship calls at ports it has never seen, on coasts where the harbourmaster speaks no language the…

The Analogy: A Ship Visiting Foreign Ports with International Signal Flags

A merchant ship calls at ports it has never seen, on coasts where the harbourmaster speaks no language the crew knows. The captain cannot assume the quay has the same cranes as home, that the berth is deep enough, or that anyone ashore will understand a shout. What saves the voyage is the International Code of Signals: a fixed set of flags whose meaning is agreed by every maritime nation. A single yellow flag means "my ship is healthy, request free pratique"; a specific hoist means "I need a pilot." The ship communicates through a vocabulary that is identical in every harbour, and before it commits to entering, it signals ahead to confirm the port actually offers what the ship will need. That is exactly the posture of a portable CI script: it cannot assume which shell, which version of the tools, or which operating system will run it, so it speaks only through a vocabulary every environment understands, and it checks what is present before it relies on it.

The heart of that shared vocabulary is the exit code. When a ship lowers its signal at the end of an evolution, the flag it flies is a promise the whole port acts on. Flying the "all is well" flag tells tugs to stand down and the harbourmaster to log a clean arrival. A disciplined captain flies the flag that matches the true state of the ship, and a specific flag for a specific trouble, because the response depends entirely on which flag is up. A CI script's exit code is that final flag: zero means the job truly succeeded, and a specific non-zero code means a specific, documented kind of failure. Every caller -- the CI runner, a wrapper script, a human reading logs -- steers on that number and nothing else.

A prudent master never assumes the local equipment. Before entering a tricky harbour the ship signals to confirm a pilot is available and consults the chart to confirm the berth will float her, rather than steaming in and discovering the problem aground. The portable-script equivalent is feature detection: ask "command -v" whether a tool exists before you build your logic on it, prefer the plain instruction every port understands over the clever manoeuvre only your home port knows, and never depend on a flag or extension that a different environment might not carry.

The failure mode arrives in two shapes, and both are quiet until they are catastrophic. The first is flying the wrong flag: a ship taking on water that still flies "all is well" gets no rescue, because the port believes the flag over the reality -- the script that exits zero while the build actually failed, so the pipeline marches on and ships broken code. The second is inventing a private flag only the home port recognises: a hoist your own crew understands but that means nothing, or something dangerous, in a foreign harbour -- the script that leans on a bashism or a GNU-only option and works perfectly on your laptop, then breaks the instant a leaner shell or a BSD userland runs it. Portability and exit discipline are the same virtue seen from two sides: say only what every environment understands, and make the one thing you say -- the exit code -- true.


Syntax or Core Structure

Exit discipline starts with treating the exit code as the script's real return value and choosing it on purpose. A function or a whole script signals success with 0 and a failure with a specific, documented non-zero number. The example below defines a check, returns 2 (misuse, by a widely followed convention) when its input is missing, and returns 0 when the input is present. Notice that "printf" is used instead of "echo -e": every shell prints "printf" the same way, while "echo" with flags behaves differently across shells and is a classic portability trap.

#!/usr/bin/env bash
set -eu

check_target() {
  target=${1:-}
  if [ -z "$target" ]; then
    printf 'error: no target given\n' >&2
    return 2
  fi
  printf 'ok: target is %s\n' "$target"
  return 0
}

check_target prod; printf 'rc=%s\n' "$?"
check_target "" || printf 'rc=%s\n' "$?"

Output:

ok: target is prod
rc=0
error: no target given
rc=2

The good call prints its success line and "rc=0". The bad call writes its message to standard error (">&2", so it never pollutes the data stream a caller might parse) and returns 2. That "|| printf" guard is deliberate: under "set -e" a bare failing command would abort the script, but a command on the left of "||" is tested rather than fatal, so we can observe the code without dying. Two habits are already visible here that carry the whole lesson -- errors go to stderr with a distinct exit code, and every construct used ("printf", "[ -z ]", "$?") is plain POSIX that any shell honours identically.


Technical Depth: Speaking a Language Every Shell Understands

Bashisms and Their Portable Equivalents

A "bashism" is a construct that bash accepts but a leaner POSIX shell (dash, the "sh" that runs many container init scripts and Debian's "/bin/sh") does not. Scripts that begin "#!/bin/sh" but use bash-only syntax fail in confusing ways -- often with a bare "not found" or a silently wrong result rather than a clean error. The table below lists the traps that bite CI scripts most often and the portable form that behaves identically everywhere.

Bash-only formPortable formWhy it matters
echo -e "a\tb"printf 'a\tb\n'echo flag handling varies by shell; printf is defined
[[ $x == a* ]]case $x in a*) ;; esac[[ is not in POSIX sh at all
arr=(one two)space-split string or positional argssh has no arrays
source lib.sh. lib.shsource is a bash alias for .
function f {f() {function keyword is bash-only
${x^^}tr '[:lower:]' '[:upper:]'case-modification expansion is bash 4+

The rule of thumb: if a script must run under an unknown "/bin/sh", write to the POSIX standard and test it with a POSIX shell, not with bash. If it genuinely needs arrays or "[[", declare that honestly with "#!/usr/bin/env bash" and accept that bash must be present -- which is itself a dependency you should feature-detect rather than assume.

Feature Detection with command -v

Never assume a tool is installed just because it is on your machine. "command -v" is the portable way to ask "does this exist and can I run it?" -- it is a POSIX shell builtin, unlike "which", which is an external program that is missing on some minimal images and prints inconsistent output across systems. Redirect its output to "/dev/null" and branch on its exit status:

#!/usr/bin/env bash
set -uo pipefail
for tool in grep this_tool_does_not_exist; do
  if command -v "$tool" >/dev/null 2>&1; then
    printf '%s: found\n' "$tool"
  else
    printf '%s: MISSING\n' "$tool"
  fi
done

Output:

grep: found
this_tool_does_not_exist: MISSING

The loop treats presence as a decision, not a certainty: a missing tool becomes a clean, reported "MISSING" instead of a mid-run crash three commands later. In a real preflight you would collect the missing names and exit with a dedicated code, which is exactly what the Real World Example does.

The Language of Exit Codes

An exit code is a single byte, 0 through 255, and the shell exposes the last one as "$?". Zero is success; everything else is a failure whose meaning you assign. A few numbers are reserved by long-standing convention, and honouring them keeps your scripts legible to tools and people who never read your source.

CodeMeaningTypical source
0successa command that worked
1general errorfalse, a failed test
2misuse / bad argumentsusage errors you raise
126found but not executablepermission denied on a file
127command not founda typo or missing dependency
128+Nkilled by signal N130 = Ctrl-C (SIGINT, 2)

You can watch the shell assign these:

#!/usr/bin/env bash
set -uo pipefail
false; printf 'false -> %s\n' "$?"
(exit 42); printf 'exit 42 -> %s\n' "$?"
this_command_does_not_exist 2>/dev/null; printf 'missing -> %s\n' "$?"

Output:

false -> 1
exit 42 -> 42
missing -> 127

The lesson in the last line is the sharp one for portability: 127 is not "my script failed", it is "the shell could not find the program at all" -- almost always a missing dependency or a "PATH" that differs between your laptop and the CI runner. Reserving 0 for genuine success and choosing deliberate codes for your own failures means a caller can distinguish "the build broke" (say, 1) from "the environment is wrong" (say, 3) without parsing a single line of log text.


Real World Example: A Portable CI Preflight Check

Most CI failures are not compile errors; they are the job discovering, halfway through, that a tool is missing or an argument was never passed. A preflight script runs first, confirms the environment before any real work begins, and fails fast with a code that says precisely what went wrong. The script below checks that its required tools exist, validates that a deploy target was supplied, and exits with documented codes -- 0 for ready, 2 for a usage error, 3 for a missing dependency.

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

# Exit codes: 0 ok, 2 usage error, 3 missing dependency
required="grep awk sed"
target=${1:-}

if [ -z "$target" ]; then
  printf 'usage: preflight <target>\n' >&2
  exit 2
fi

missing=0
for tool in $required; do
  if command -v "$tool" >/dev/null 2>&1; then
    printf '  dep %-6s ok\n' "$tool"
  else
    printf '  dep %-6s MISSING\n' "$tool"
    missing=$((missing + 1))
  fi
done

if [ "$missing" -gt 0 ]; then
  printf 'preflight FAILED: %s dependency missing\n' "$missing" >&2
  exit 3
fi

printf 'preflight OK for target %s\n' "$target"
exit 0

Output:

  dep grep   ok
  dep awk    ok
  dep sed    ok
preflight OK for target staging

Run as "preflight staging" on a host that has the three tools, it reports each dependency and exits 0, so the CI runner proceeds. Run with no argument, it writes "usage: preflight <target>" to stderr and exits 2; run where "awk" is absent, it prints the MISSING line, then "preflight FAILED: 1 dependency missing" to stderr, and exits 3. A wrapper can now branch on the code alone -- retry on 3 after installing tools, but never retry a 2, because a usage error will fail identically forever. The messages are for humans; the exit code is for machines, and they never disagree.

The portability discipline shows in the details. "printf" is used throughout rather than "echo -e", so tab and newline handling is identical under any shell. "command -v" is a builtin, so the check itself needs no external program. Diagnostics go to stderr with ">&2", keeping standard output clean for any caller that captures it. And the exit codes are stated in a comment at the top, turning an implicit convention into a documented contract.

The script is also honestly limited, and the deepest flaw is one every portable script must respect: presence is not compatibility. "command -v sed" passing proves only that a program named "sed" exists -- it does not prove it is GNU sed, so a later "sed -i" or an extended-regex flag can still fail on a BSD or busybox userland that named its tool the same. Checking that a tool exists is a weaker guarantee than checking it behaves the way you need. Three lesser flaws compound this. The loop iterates "$required" by unquoted word-splitting, which is convenient but relies on "IFS" and breaks the moment a tool name contains a space. The target is only checked for emptiness, so a typo like "stagng" sails through as a perfectly valid string. And the exit-code contract lives in a comment, not in any enforcement -- nothing stops a future edit from adding an "exit 4" that no caller was ever told about, which is precisely the "private flag" failure the analogy warned of. A production version would probe capability rather than mere presence (run "sed --version" or test a real invocation), quote its iteration, and validate the target against a known set.


Common Mistakes

  1. Exiting 0 after a step already failed. Capturing a command's output, ignoring its status, and falling through to a final "exit 0" is the wrong-flag disaster: the pipeline believes the green light and ships broken code. Let the real exit code propagate, or set it deliberately.
  1. Relying on "echo -e" or "echo" flags. Whether "echo" interprets "\n" or prints it literally depends on the shell and even on shell options. "printf" has one defined behaviour everywhere; use it for anything with escapes or formatting.
  1. A "#!/bin/sh" shebang over bash-only syntax. Writing "[[", arrays, or "${x^^}" under a "sh" shebang works on systems where "/bin/sh" happens to be bash, then breaks on Debian or Alpine where it is dash or busybox. Match the shebang to the syntax you actually use.
  1. Using "which" to test for a tool. "which" is an external command that is absent on minimal images and prints differently across systems. "command -v" is a POSIX builtin and is the correct, portable feature-detection tool.
  1. Assuming GNU flags exist. "sed -i", "grep -P", "date -d", and "readlink -f" are GNU extensions missing or different on BSD and macOS. A script that works on your CI's Linux runner can fail on a developer's Mac using the same "sed" name.
  1. Collapsing all failures into one code. Returning 1 for every problem forces callers to parse logs to decide whether to retry. Distinct codes -- environment wrong versus build broken versus bad usage -- let a wrapper react correctly on the number alone.
  1. Writing errors to stdout. Diagnostics on standard output corrupt any caller that captures stdout as data. Send every human-facing message to stderr with ">&2" and keep stdout for the result.
  1. Trusting "set -e" to catch everything. "set -e" does not abort on a failure inside an "if" test, on the left of "||", inside command substitution, or (without "set -o pipefail") on an early command in a pipeline. Do not assume it guards code it structurally cannot see.
  1. Hardcoding tool paths. Writing "/usr/bin/python" or "/bin/grep" assumes a layout that differs across distributions and containers. Rely on "PATH" plus a "command -v" check so the script finds the tool wherever it actually lives.

Best Practices

  • Match the shebang to the syntax. Use "#!/usr/bin/env bash" when you genuinely need bash features, and "#!/bin/sh" only for code you have kept strictly POSIX. Never mix a "sh" shebang with bash-only constructs.
  • Open with strict mode and know its limits. Start bash scripts with "set -euo pipefail" (or "set -eu" under POSIX "sh"), then remember where "set -e" cannot help and guard those spots explicitly.
  • Feature-detect before you depend. Gate any external tool behind a "command -v" check and fail with a clear, dedicated exit code when it is missing, rather than crashing mid-run.
  • Choose exit codes on purpose and document them. Reserve 0 for true success, assign distinct non-zero codes to distinct failure classes, and list them in a header comment so the contract is explicit.
  • Separate the streams. Send every diagnostic to stderr with ">&2" and reserve stdout for the script's actual result, so callers can capture data without swallowing error text.
  • Prefer "printf" to "echo". For anything involving escapes, alignment, or portability, "printf" behaves identically across shells while "echo" does not.
  • Quote expansions and control "IFS". Wrap variable uses in double quotes and set "IFS" deliberately when you split, instead of leaning on the default word-splitting that varies with the environment.
  • Test on the leanest target, not your laptop. Run the script under the actual CI image or a minimal shell like dash before trusting it; the environment that will run it in anger is the one that matters.

Practice Exercises

  1. Portability audit. Take a script that uses "echo -e", "[[ ... ]]", and "which foo", and rewrite each construct into a POSIX-portable equivalent. Verify the rewrite by running it under "dash" (or "sh") and confirming identical output and exit status.
  1. Extend the exit-code contract. Add a fourth code to the preflight script -- 4 for "target is not in the allowed set" -- validate the argument against a fixed list, document the new code in the header comment, and write a wrapper that retries only on code 3 and never on 2 or 4.
  1. Capability, not presence. Modify the dependency check so that instead of only confirming a tool exists, it confirms the tool supports a flag you actually need (for example by running it once with "--version" or a harmless probe invocation) and reports a tool that is present but incompatible.
  1. Cleanup that preserves the code. Write a script that creates a temporary file, installs "trap 'rm -f "$tmp"' EXIT" to remove it, and then fails partway through. Prove that the temporary file is deleted and that the script's final exit code reflects the failure, not the cleanup.