Around Go: command line · 3 MIN READ

Pipelines, exit codes and explicit failure handling

Read pipeline failure behavior and keep configuration and secrets out of command strings.

A script is another program with success and failure paths. A command printing plausible output can still fail. Pipelines complicate this because the last command can succeed even when an earlier producer failed.

01

Observe the whole pipeline

Bash pipefail makes a pipeline fail when a component fails, instead of using only the final command's status. Check that status explicitly at the workflow boundary. set -e has exceptions in conditionals and other constructs, so it is not a replacement for understanding control flow.

bash
#!/usr/bin/env bash
set -u -o pipefail
if go test ./... | tee test.log; then
    printf "%s\n" "Tests passed"
else
    printf "%s\n" "Tests failed; inspect test.log" >&2
    exit 1
fi
Read the code

tee preserves a log while showing output. With pipefail, a failing go test makes the condition fail even when tee succeeds. This script is for a trusted local project and writes one named log file.

02

Pass configuration and inspect one setting

A prefix assignment belongs to one child process; export passes a variable to later children from this shell. Check selected non-secret settings instead of dumping the full environment. Already-running services keep their original environment.

bash
APP_ENV=development go run ./cmd/api
export APP_ENV=development
printf "APP_ENV=%s\n" "$APP_ENV"
command -v go
Read the code

The first line runs a foreground API until you stop it; execute the following commands after it exits or in another shell. The example assumes cmd/api exists and does not require a credential. command -v shows which Go executable Bash will resolve.

03

Make cleanup and retries deliberate

A trap can arrange cleanup of resources a script created, but it cannot roll back an external side effect automatically. Avoid rerunning a deployment simply because its status command timed out. Keep a stable operation identifier and inspect the outcome before retrying. As a script grows, move complex state transitions into a program with tests.

TAKE THIS WITH YOU

A successful last pipeline command does not prove upstream success. Preserve exit status, handle failure explicitly, and avoid exposing configuration secrets.

Check your understanding

Which statement is correct about bash pipefail?

Go to the source

Progress stays in this browser. No account needed.