CI/CD Automation

CI/CD Automation in Bash: Picture a narrowboat at the bottom of a canal staircase -- a flight of connected locks that climbs a steep hillside, each chamber…

The Analogy: A Boat Ascending a Canal Staircase Lock

Picture a narrowboat at the bottom of a canal staircase -- a flight of connected locks that climbs a steep hillside, each chamber emptying directly into the one below it. The boat cannot leap to the top. It enters the first chamber, the lower gate closes behind it, and the keeper lets water in until the level inside matches the pound above. Only when the levels are equal can the upper gate swing open and the boat move up into the next chamber. Every lock is a gate that must be passed, in order, before the one above it will even open.

A CI/CD pipeline is exactly this staircase. The commit is the boat, and each stage -- lint, then test, then build, then deploy -- is a lock chamber. The boat rises one stage at a time, and each stage must succeed completely before the next gate opens. A shell script drives the flight: it announces which chamber the boat is entering, runs the work for that stage, and checks the result. If the work passes, the gate opens and the boat proceeds; if it fails, the gate stays shut and the boat goes no higher.

The keeper does not just operate the gates; the keeper keeps a log. Every boat that passes, the time each chamber took, which gate jammed -- all of it goes in the book, so that anyone downstream can see how the ascent went without having stood at the lockside. Your pipeline script plays the keeper's role too: it prints a running commentary as each stage starts, records whether each one passed or failed, and ends with a summary and a single overall verdict -- success or failure -- that the outside world can read from one number, the script's exit code.

The failure mode is the keeper who opens a gate too early. If the upper gate is cracked before the chamber has filled, water surges down from the pound above, the boat lurches, and in the worst case it grounds on the cill as the level drops. A pipeline that opens its final gate -- deploy -- before the earlier chambers have truly filled does the same violence: it ships an artifact whose tests never really passed, and production takes the surge. Just as damaging is the keeper who logs a successful passage while a lower gate was quietly leaking: a pipeline that reports SUCCESS while swallowing a stage's true exit code sends a broken boat up the flight with a clean record behind it.


Syntax or Core Structure

At its simplest, a pipeline script is a list of stages that must all succeed. The set -euo pipefail line at the top is what makes the flight of locks behave: -e aborts the whole script the instant any command returns non-zero, so a failing stage stops the ascent instead of letting the next gate open. Each stage announces itself, does its work, and the shell itself enforces the gate.

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

echo "==> lint"
true

echo "==> test"
true

echo "==> build"
true

echo "pipeline ok"

Output:

==> lint
==> test
==> build
pipeline ok

Here every stage is stubbed with true, which always succeeds, so the boat rises through all three chambers and the final echo runs. The script's exit code is 0, the single number a CI system reads to decide the build is green. Replace any true with false and set -e halts the script at that line: the later stages never print, and the exit code becomes non-zero. That is the entire contract of a pipeline -- run the stages in order, stop at the first failure, and report the verdict through the exit code.


Technical Depth: Gates, Exit Codes, and the Keeper's Log

The exit code is the whole language of a pipeline. Zero means the gate may open; anything else means it stays shut. The art is choosing, for each stage, whether a failure should slam the whole flight closed or merely be noted in the log.

When set -e is too blunt

With set -e, the first failing command ends everything, and nothing after it runs -- not even a summary.

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

echo "==> lint"
false
echo "this line never runs"

Output:

==> lint

The script prints the lint header, false returns 1, and set -e terminates the script with exit code 1 before the second echo. This is perfect for a strict "stop at the first crack" pipeline, but it has a cost: you cannot run four stages, let two fail, and print a report of all four, because the script is already dead after the first failure. When you need the keeper's full log, you must handle exit codes yourself instead of letting set -e do it.

Four ways to treat a stage's exit code

Bash offers several constructs for reacting to a non-zero status, and a pipeline uses each in different places.

ConstructReaction to a non-zero exitAborts the script?
set -eends the script at onceyes
if cmd; then ...; else ...; firuns the else branchno
cmd with an or-else fallbackruns the fallback commandno
cmd; rc=$?records the status in rc for laterno

The third row is the || form, written cmd || handler: if cmd fails, handler runs and the script carries on. The if form and the || form are the two everyday ways to observe a failure without obeying it, while cmd; rc=$? is the way to stash the exact code for a later decision. A pipeline typically uses set -e for the strict spine of the flight and reaches for the if or || forms only in the specific places where it wants to catch a failure, log it, and keep going -- to run a cleanup step, say, or to record a stage's result before deciding whether to halt the whole ascent.

Capturing a status without aborting

To note a result and keep going, wrap the command in an if, or read $? on the very next line before anything else overwrites it. Here the script asks whether a build line contained FAIL and reports the answer without dying:

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

if grep -q 'FAIL' <<< 'build: ok'; then
  echo "found FAIL"
else
  echo "no FAIL (rc was $?)"
fi

Output:

no FAIL (rc was 1)

Note that this script uses set -uo pipefail but not -e: with -e in force, the failing grep would abort before the else branch could report anything. Inside the else, $? is the exit code of the if condition -- grep returning 1 because it found no match. This is the pattern for any stage whose failure you want to record rather than obey.

A reusable stage runner

Wrapping the repetition in a function keeps each stage to one line and centralises the announcing and checking. The runner prints the header, runs whatever command it is handed, and turns a non-zero exit into a clear failure line.

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

run_stage() {
  local name=$1; shift
  echo "==> $name"
  if "$@"; then
    echo "    $name: ok"
  else
    echo "    $name: FAILED (rc=$?)"
    return 1
  fi
}

run_stage lint true
run_stage test true
run_stage deploy false || echo "pipeline stopped at deploy"

Output:

==> lint
    lint: ok
==> test
    test: ok
==> deploy
    deploy: FAILED (rc=1)
pipeline stopped at deploy

The function takes the stage name as its first argument, shifts it away, and runs the rest as the actual command with "$@". Because the failure is caught by the calling || echo ..., the script itself does not abort, so the runner is a building block you can call in a loop and still produce a summary at the end.


Real World Example: A Pipeline Runner with a Summary

A real pipeline wants both behaviours at once: stop the boat at the first jammed gate, and print a log of every chamber it visited. The runner below walks a fixed list of stages, checks each stage's outcome, stops at the first failure with break, and then prints a summary table and one overall verdict. It deliberately runs under set -uo pipefail without -e, because it needs to survive a failing stage long enough to report it. The stage outcomes are held in an associative array here only to keep the example self-contained; in a live pipeline each would be a real command such as shellcheck, bats, or docker build.

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

stages=(lint test build package)
declare -A outcome=( [lint]=0 [test]=0 [build]=1 [package]=0 )

failed=0
declare -a results=()
for stage in "${stages[@]}"; do
  echo "==> running: $stage"
  if [[ "${outcome[$stage]}" -eq 0 ]]; then
    results+=("$stage PASS")
  else
    results+=("$stage FAIL")
    failed=$((failed + 1))
    break
  fi
done

echo "----- summary -----"
for r in "${results[@]}"; do
  printf '%-10s %s\n' "${r% *}" "${r#* }"
done
echo "-------------------"
if [[ "$failed" -eq 0 ]]; then
  echo "result: SUCCESS"
  exit 0
else
  echo "result: FAILURE ($failed stage failed)"
  exit 1
fi

Output:

==> running: lint
==> running: test
==> running: build
----- summary -----
lint       PASS
test       PASS
build      FAIL
-------------------
result: FAILURE (1 stage failed)

The loop visits the stages in the fixed order of the stages array, which is what makes the ascent deterministic. For each stage it reads the outcome, and on a pass it appends a "name PASS" record to the results array; on a fail it appends "name FAIL", bumps the failed counter, and breaks out of the loop. The summary loop then splits each record back into name and status using parameter expansion -- ${r% *} strips the trailing status to leave the name, ${r#* } strips the leading name to leave the status -- and printf aligns them into a table. The final if turns the failed count into a one-word verdict and, crucially, the matching exit code.

Reading the run is immediate: lint and test filled their chambers and passed, build jammed, and the boat stopped there. Because the loop broke at build, the fourth stage package never ran and does not appear in the summary at all. The verdict is FAILURE, and the script exits 1, so any CI system calling this script sees a red build from that single number without parsing the text.

The design has real limits worth naming. The fail-fast break is a genuine trade-off, not a free win: because the run stops at build, you never learn whether package would also have failed, so a developer might fix build, re-run, and only then discover a second broken stage -- two round trips where a non-fail-fast run would have shown both at once. The status parsing leans on splitting at a space, so a stage whose name contained a space would be torn apart by ${r% *}. And the outcome lookup ${outcome[$stage]} has no default: under set -u, listing a stage in stages that is missing from the outcome map does not skip it -- it aborts the whole script with an "unbound variable" error mid-flight, exactly the leaking-gate failure the analogy warns about, because a configuration gap masquerades as a crash rather than a clear message.


Common Mistakes

  1. Expecting a summary while relying on set -e. With -e the script dies at the first failing stage, so any report you meant to print at the end never runs. Handle exit codes yourself when you need a log of every stage.
  2. Forgetting that set -e is suppressed in a condition. A command that fails inside if cmd; then, or on the left of && or ||, does not abort the script. Relying on -e to catch such a failure silently lets it through.
  3. Omitting pipefail. Without it, false | true exits 0, because a pipeline reports only its last command's status. A failing test whose output is piped into tee would look green. Always set pipefail when a stage is a pipeline.
  4. Printing "FAILURE" but exiting 0. CI reads the exit code, not your text. A script that describes a failure but returns zero marks the build green. Every failure path must end in a non-zero exit.
  5. Reading $? too late. $? holds only the most recent command's status. An echo between the stage and rc=$? overwrites it with the echo's exit code. Capture $? on the very next line.
  6. Setting a failure flag inside a piped loop. cmd | while ...; do failed=1; done sets failed in a subshell, so the parent still sees it unset. Feed the loop with < <(cmd) so the flag survives.
  7. Chaining every stage with &&. lint && test && build && deploy works but reports nothing per stage and becomes unreadable. A loop with named stages and a summary is far easier to debug.
  8. Failing to quote "$@" in a stage runner. Passing the command unquoted word-splits any argument containing spaces, so a stage invoked with a path or message that has a space runs the wrong command.
  9. Hiding stage output. Redirecting a stage's stderr to /dev/null to keep the log tidy means that when it fails, there is no diagnostic to read. Keep failing stages' output; suppress only known-noisy success chatter.

Best Practices

  • Open every pipeline script with set -euo pipefail. It is the safe default -- fail on error, fail on undefined variable, fail on a broken pipe stage -- and you drop -e only deliberately, for a loop that must survive to print a summary.
  • Give each stage a named runner. A run_stage name cmd... helper makes every stage log identically and keeps the pipeline body to one readable line per gate.
  • Make the exit code the single source of truth. End the script exit 0 only when every stage truly passed, and exit 1 (or the stage's own code) on any failure. CI trusts the number, not the prose.
  • Announce each stage and summarise at the end. A header before every gate and a table afterwards turn the log into something a tired engineer can read at a glance during an incident.
  • Set pipefail before any staged pipeline. So that a failure anywhere in a | b | c is not masked by a succeeding final command.
  • Drive gates from real exit codes, not parsed output. Test the command's status directly rather than grepping its text for the word "error", which misses failures that print nothing.
  • Decide fail-fast per pipeline, not by habit. Gate-style deploys should stop at the first failure, but independent checks -- lint, format, unit tests -- are often more useful run to completion so one run reports every problem.
  • Give lookups a default so gaps are messages, not crashes. Writing ${outcome[$stage]:-unknown} turns a missing entry into a handled case instead of an "unbound variable" abort under set -u.

Practice Exercises

  1. Green then red. Write a fail-fast pipeline of three stubbed stages under set -euo pipefail, confirm it exits 0 when all pass, then flip one stage to false and show that the later stages do not print and the exit code becomes non-zero.
  2. Summary without set -e. Rewrite that pipeline to run under set -uo pipefail without -e, collect a PASS or FAIL record per stage in an array, print an aligned summary table, and exit non-zero if any stage failed.
  3. Prove pipefail matters. Show false | true exiting 0 with pipefail off and 1 with it on, and explain in one sentence what a CI system would conclude about the build in each case.
  4. Skip instead of crash. Extend the pipeline runner so that a stage listed in stages but missing from the outcome map is reported as SKIP -- using a :- default in the lookup -- rather than aborting under set -u. Show the output with one skipped stage.