Using Bash in CI/CD Pipelines
Continuous integration (CI) means that every change pushed to a repository is automatically checked: the code is built, linted and tested on a fresh machine, and the change is marked as passing or failing. Continuous delivery or deployment (CD) extends this, so that changes that pass are packaged and released automatically. Systems such as GitHub Actions, GitLab CI/CD, Jenkins and Bitbucket Pipelines differ in their configuration formats, but almost all of the actual work in them is done by shell commands, and on Linux runners that shell is usually Bash.
This lesson explains how CI systems run shell commands, which Bash settings decide whether a failure stops the pipeline, how scripts detect and use the CI environment, and why the pipeline logic belongs in a script in the repository rather than in the CI configuration file. It ends with a pipeline script that runs unchanged on a developer's machine, in GitHub Actions and in GitLab CI.
How a CI System Runs Your Commands
A CI configuration file describes jobs made of steps. A step that runs commands looks like this in GitHub Actions:
- name: Run tests
run: |
echo "running tests"
tests/run_all.sh
and like this in GitLab CI:
test:
script:
- echo "running tests"
- tests/run_all.sh
The runner, the machine or container that executes the job, writes these commands into a temporary script and runs it with a shell. Three facts follow from this, and they explain most surprises in CI:
- The exit status decides the result. A step passes when its script exits with 0 and fails otherwise. Output such as
ERRORin the log does not fail a step; only the exit status does. - The shell options come from the CI system. In GitHub Actions,
shell: bashruns the script asbash --noprofile --norc -eo pipefail {0}, while a step without ashell:setting on a Linux runner runs asbash -e {0}.{0}stands for the temporary script file. - Every job starts on a fresh machine or container, with nothing from earlier jobs except what the pipeline explicitly passes on, and without a terminal or a person to answer questions.
Why the shell options matter
The difference between bash -e and bash -eo pipefail changes which failures are noticed. set -e stops a script when a command fails, but the exit status of a pipeline is the status of its last command; pipefail makes a pipeline fail when any command in it fails (lessons 119 and 120). This step counts errors in a build log that, by mistake, does not exist:
echo "step starts"
grep -c ERROR missing-build.log | tee error-count.txt
echo "step continues after the pipeline"
Run the way GitHub Actions runs a step without shell:, and the way it runs one with shell: bash:
bash -e step.sh; echo "[status $?]"
bash --noprofile --norc -eo pipefail step.sh; echo "[status $?]"
step starts
grep: missing-build.log: No such file or directory
step continues after the pipeline
[status 0]
step starts
grep: missing-build.log: No such file or directory
[status 2]
With -e alone, grep failed but tee succeeded, so the pipeline succeeded, the script continued, and the step was reported as passed, with an empty error-count.txt. With pipefail, the step stopped and failed with grep's status 2. The safe approach is not to depend on how the CI system starts the shell at all: put the commands in a script that sets its own options with set -euo pipefail in its first lines. The script then behaves the same in every CI system and on a laptop.
No terminal, no questions
CI jobs run without a terminal and with standard input that is empty or closed. A command that waits for an answer either fails or hangs until the job's time limit. read returns a non-zero status at end of input:
bash -c '[[ -t 0 ]] && echo "stdin is a terminal" || echo "stdin is not a terminal"' < /dev/null
bash -c 'read -r -p "Continue? [y/N] " answer; echo "[read status $?, answer=\"$answer\"]"' < /dev/null
stdin is not a terminal
[read status 1, answer=""]
Commands used in CI must therefore be non-interactive: apt-get install -y with DEBIAN_FRONTEND=noninteractive, docker run without -t (lesson 175), and options such as --yes or --batch for tools that would otherwise ask for confirmation. Scripts that prompt users can use [[ -t 0 ]] to detect the situation and either use a default or fail with a clear message.
Keep the Logic in Scripts
A CI configuration file can contain long shell programs inside its run: or script: blocks, but that has real costs: the commands cannot be run locally without copying them out of YAML, they cannot be checked by bash -n or ShellCheck, YAML's own quoting rules interact with the shell's, and moving to another CI system means rewriting them. The common structure is therefore:
- the repository contains scripts such as
ci/run.shorscripts/test.shwith all the logic; - the CI configuration only prepares the environment (checkout, tool versions, secrets) and calls those scripts.
A developer can then reproduce a failed pipeline by running the same script locally, and the CI configuration stays short. The complete example at the end of this lesson follows this structure.
The CI Environment
CI systems describe the run through environment variables. Some useful ones:
| Purpose | GitHub Actions | GitLab CI |
|---|---|---|
| running in CI at all | CI=true | CI=true |
| which system | GITHUB_ACTIONS=true | GITLAB_CI=true |
| commit being built | GITHUB_SHA | CI_COMMIT_SHA |
| branch or tag name | GITHUB_REF_NAME | CI_COMMIT_REF_NAME |
| repository checkout | GITHUB_WORKSPACE | CI_PROJECT_DIR |
| run identifier | GITHUB_RUN_ID | CI_PIPELINE_ID |
CI=true is a widespread convention: many tools change their behaviour when it is set, for example by disabling colours, progress bars or interactive prompts. A script can use these variables to adapt, and fall back to git commands when they are missing, which is the case on a developer's machine:
sha=${GITHUB_SHA:-${CI_COMMIT_SHA:-$(git rev-parse HEAD)}}
The nested ${VAR:-default} expansions (lesson 45) try GitHub's variable, then GitLab's, then ask git.
Talking to the CI System
Besides the exit status, CI systems offer ways for a script to structure its log and pass information on. They are triggered by plain text output or by writing to special files.
GitHub Actions
GitHub Actions recognizes workflow commands, lines on standard output that start with :::
echo "::group::Install dependencies" # start a collapsible section in the log
echo "::endgroup::" # end it
echo "::error file=lib/slug.sh,line=9::syntax error" # error annotation shown on the file
echo "::warning::cache not found, building from scratch"
echo "::add-mask::$api_token" # hide this value in all later log output
Error and warning annotations appear on the run's summary page and, with file and line, next to the code in pull requests. Other information is passed by appending to files whose paths are in environment variables:
| Variable | What appending to the file does |
|---|---|
GITHUB_OUTPUT | name=value lines become outputs of the step, read later as steps.<id>.outputs.name |
GITHUB_ENV | NAME=value lines become environment variables in all later steps of the job |
GITHUB_PATH | each line is a directory added to PATH for later steps |
GITHUB_STEP_SUMMARY | Markdown shown on the run's summary page |
echo "version=1.4.0" >> "$GITHUB_OUTPUT"
echo "BUILD_MODE=release" >> "$GITHUB_ENV"
echo "### Build finished" >> "$GITHUB_STEP_SUMMARY"
Values containing newlines need the delimiter syntax name<<DELIMITER, followed by the lines and a line containing only the delimiter.
GitLab CI
GitLab collapses log sections marked by special lines containing terminal escape sequences:
printf '\e[0Ksection_start:%s:%s[collapsed=true]\r\e[0K%s\n' "$EPOCHSECONDS" install "Install dependencies"
printf '\e[0Ksection_end:%s:%s\r\e[0K\n' "$EPOCHSECONDS" install
The section name (install) links the start and end lines, and the timestamps let GitLab show how long the section took. To pass values to later jobs, a job writes NAME=value lines to a file and declares it as a dotenv report in its artifacts: configuration; the variables are then defined in the jobs that depend on it.
Retrying Flaky Network Operations
Downloads from package registries and other services occasionally fail for reasons that have nothing to do with the change being tested. Retrying them a few times, with an increasing delay, avoids failed pipelines caused by a brief outage. Tests must not be retried this way: a test that only passes sometimes points to a real problem.
# retry ATTEMPTS COMMAND...: run COMMAND until it succeeds, at most ATTEMPTS times,
# waiting 2, 4, 8... seconds between attempts
retry() {
local attempts=$1 n=1 delay=2
shift
until "$@"; do
if (( n >= attempts )); then
echo "retry: '$*' failed $n times, giving up" >&2
return 1
fi
echo "retry: '$*' failed (attempt $n of $attempts), retrying in ${delay}s" >&2
sleep "$delay"
n=$(( n + 1 )) delay=$(( delay * 2 ))
done
}
The command and its arguments are passed as separate words and run as "$@", so arguments with spaces stay intact (lesson 89). A test function flaky that succeeds only on its third call shows both outcomes:
retry 5 flaky; echo "[status $?]"
retry 2 flaky; echo "[status $?]"
download attempt 1
retry: 'flaky' failed (attempt 1 of 5), retrying in 2s
download attempt 2
retry: 'flaky' failed (attempt 2 of 5), retrying in 4s
download attempt 3
[status 0]
download attempt 1
retry: 'flaky' failed (attempt 1 of 2), retrying in 2s
download attempt 2
retry: 'flaky' failed 2 times, giving up
[status 1]
In a real pipeline it would wrap commands like retry 3 curl -fsSLo tool.tar.gz "$url". curl -f matters here: without it, curl exits with 0 even when the server answers with an HTTP error.
Secrets in CI Logs
CI systems inject secrets such as deployment keys and API tokens as environment variables and try to replace their values with *** in the log. That masking works only for the exact value: a secret that is base64-encoded, split, or printed as part of a URL may appear in clear text. Scripts should therefore never print secrets, and in particular must not run set -x while secrets are in variables, because tracing prints every expanded command (lesson 158). Values derived from a secret can be masked explicitly in GitHub Actions with ::add-mask::.
A Complete Example: One Pipeline Script for Every CI System
The example project is a small Bash tool, slug, which turns text into URL slugs. Its repository contains a library, a command, a test file and the pipeline script:
bin/slug the command
lib/slug.sh the slugify function
tests/test_slug.sh tests; exits 1 if a case fails
ci/run.sh the pipeline
ci/run.sh runs three stages: lint checks every script's syntax, test runs the tests, and package builds a versioned archive with a checksum. Small adapter functions translate log groups, error annotations, outputs and summaries into the conventions of whichever system runs the script.
#!/usr/bin/env bash
#
# ci/run.sh - the project's CI pipeline: lint, test and package
#
# Usage: ci/run.sh [STAGE...] stages: lint test package (default: all three)
#
# The same script runs on a laptop, in GitHub Actions and in GitLab CI.
# It detects where it runs and uses that system's features for log groups,
# error annotations and outputs; locally it prints plain text.
set -euo pipefail
cd "$(dirname "$0")/.."
# --- adapters for the CI system ------------------------------------------------
if [[ ${GITHUB_ACTIONS:-} == true ]]; then ci=github
elif [[ ${GITLAB_CI:-} == true ]]; then ci=gitlab
else ci=local
fi
group_start() { # group_start ID TITLE: begin a collapsible block in the log
case $ci in
github) echo "::group::$2" ;;
gitlab) printf '\e[0Ksection_start:%s:%s[collapsed=true]\r\e[0K%s\n' "$EPOCHSECONDS" "$1" "$2" ;;
local) printf '== %s\n' "$2" ;;
esac
}
group_end() { # group_end ID
case $ci in
github) echo "::endgroup::" ;;
gitlab) printf '\e[0Ksection_end:%s:%s\r\e[0K\n' "$EPOCHSECONDS" "$1" ;;
local) ;;
esac
}
annotate() { # annotate FILE LINE MESSAGE: report an error at a source location
if [[ $ci == github ]]; then
echo "::error file=$1,line=$2::$3"
else
echo "error: $1:$2: $3" >&2
fi
}
set_output() { # set_output NAME VALUE: hand a value to later steps or jobs
case $ci in
github) echo "$1=$2" >> "$GITHUB_OUTPUT" ;;
gitlab) echo "$1=$2" >> ci-outputs.env ;; # declared as a dotenv report
local) echo "output: $1=$2" ;;
esac
}
summary() { # summary LINE...: add Markdown to the run's summary page
if [[ $ci == github ]]; then printf '%s\n' "$@" >> "$GITHUB_STEP_SUMMARY"; fi
}
# --- stages ----------------------------------------------------------------------
stage_lint() {
local f out bad=0 line
for f in bin/* lib/*.sh tests/*.sh ci/*.sh; do
if ! out=$(bash -n "$f" 2>&1); then
bad=$(( bad + 1 ))
# bash -n reports "FILE: line N: MESSAGE"; split that into its parts
line=$(sed -n '1s/^.*: line \([0-9]*\): .*$/\1/p' <<< "$out")
annotate "$f" "${line:-1}" "$(sed -n '1s/^.*: line [0-9]*: //p' <<< "$out")"
fi
done
echo "checked $(compgen -G 'bin/*' | wc -l) commands and $(compgen -G '*/*.sh' | wc -l) scripts, $bad with errors"
(( bad == 0 ))
}
stage_test() {
local t failed=()
for t in tests/test_*.sh; do
if bash "$t"; then :; else failed+=("$t"); fi
done
if (( ${#failed[@]} )); then
annotate "${failed[0]}" 1 "${#failed[@]} test file(s) failed: ${failed[*]}"
return 1
fi
}
stage_package() {
local version sha artifact
version=$(git describe --tags --always --dirty)
sha=${GITHUB_SHA:-${CI_COMMIT_SHA:-$(git rev-parse HEAD)}}
artifact=dist/slug-$version.tar.gz
mkdir -p dist
tar -czf "$artifact" bin lib
( cd dist && sha256sum "${artifact#dist/}" > "${artifact#dist/}.sha256" )
echo "built $artifact ($(stat -c %s "$artifact") bytes) from commit ${sha:0:12}"
set_output version "$version"
set_output artifact "$artifact"
summary "Packaged **$version** as \`$artifact\`."
}
# --- run the requested stages -------------------------------------------------------
if (( $# )); then stages=("$@"); else stages=(lint test package); fi
rows=() status=0
for stage in "${stages[@]}"; do
declare -F "stage_$stage" > /dev/null || { echo "unknown stage: $stage" >&2; exit 2; }
group_start "$stage" "Stage: $stage"
start=${EPOCHREALTIME/[.,]/} # microseconds since the epoch
if "stage_$stage"; then result=passed; else result=FAILED; fi
tenths=$(( (${EPOCHREALTIME/[.,]/} - start) / 100000 ))
secs=$(( tenths / 10 )).$(( tenths % 10 ))
group_end "$stage"
echo "stage $stage: $result (${secs}s)"
rows+=("| $stage | $result | ${secs}s |")
if [[ $result == FAILED ]]; then status=1; break; fi
done
summary "" "| Stage | Result | Time |" "|---|---|---|" "${rows[@]}"
exit "$status"
How It Works
- Strict mode and a fixed working directory.
set -euo pipefailmakes the script independent of the options the CI system uses, andcd "$(dirname "$0")/.."makes paths relative to the repository root, wherever the script is started from. - Detection, then adapters. The script decides once whether it runs in GitHub Actions, GitLab CI or locally, and the five adapter functions contain all system-specific behaviour. The stages call only the adapters, so supporting another CI system means adding cases to the adapters, not changing the stages.
- Stages are functions named
stage_NAME.declare -F "stage_$stage"checks that a function with that name exists, soci/run.sh deployfails with a clear message instead of a "command not found" error. Calling"stage_$stage"insideifis deliberate: in the condition of anif,set -eis disabled, so a failing stage is recorded asFAILEDinstead of ending the script before the summary is written. - Lint runs
bash -n, which parses a script without executing it, on every script. Its messages have the formFILE: line N: MESSAGE; twosedexpressions extract the line number and the message, so the annotation points to the right line. ShellCheck (lesson 162) finds many more problems and is the natural next addition to this stage. - Test runs each test file in its own
bashprocess, collects the failures, and reports them all before failing. - Package names the archive after
git describe --tags --always --dirty, which produces versions such asv1.4.0-4-gdd8884c(four commits after tagv1.4.0, at commitdd8884c), adds-dirtywhen tracked files have uncommitted changes, and falls back to the commit hash when there are no tags. The checksum is created from insidedist, so the.sha256file contains just the file name and can be checked later withsha256sum -c. - Timing without external tools.
$EPOCHREALTIMEcontains the time with microseconds, such as1796099411.482913. Removing the decimal separator ([.,], because some locales use a comma) gives an integer number of microseconds that Bash arithmetic can subtract. - The first failing stage ends the run, and the exit status tells the CI system whether the job passed.
Running the Complete Example
On a developer's machine, without any CI variables, the script prints plain text:
$ ci/run.sh
== Stage: lint
checked 1 commands and 3 scripts, 0 with errors
stage lint: passed (0.0s)
== Stage: test
ok - 'Hello World'
ok - ' Bash & CI/CD '
ok - 'Already-a-slug'
ok - 'Version 2.0'
stage test: passed (0.0s)
== Stage: package
built dist/slug-v1.4.0-2-g629da11.tar.gz (451 bytes) from commit 629da11a453d
output: version=v1.4.0-2-g629da11
output: artifact=dist/slug-v1.4.0-2-g629da11.tar.gz
stage package: passed (0.0s)
[status 0]
To see what GitHub Actions receives, the GitHub variables were set by hand, with GITHUB_OUTPUT and GITHUB_STEP_SUMMARY pointing to ordinary files:
export GITHUB_ACTIONS=true GITHUB_OUTPUT=/tmp/gh_output GITHUB_STEP_SUMMARY=/tmp/gh_summary.md
ci/run.sh
::group::Stage: lint
checked 1 commands and 3 scripts, 0 with errors
::endgroup::
stage lint: passed (0.0s)
::group::Stage: test
ok - 'Hello World'
ok - ' Bash & CI/CD '
ok - 'Already-a-slug'
ok - 'Version 2.0'
::endgroup::
stage test: passed (0.0s)
::group::Stage: package
built dist/slug-v1.4.0-3-g3c4afc2.tar.gz (451 bytes) from commit 3c4afc20dcee
::endgroup::
stage package: passed (0.0s)
[status 0]
GitHub shows each ::group:: as a collapsed section in the log. The output file and the summary file then contained:
version=v1.4.0-3-g3c4afc2
artifact=dist/slug-v1.4.0-3-g3c4afc2.tar.gz
Packaged **v1.4.0-3-g3c4afc2** as `dist/slug-v1.4.0-3-g3c4afc2.tar.gz`.
| Stage | Result | Time |
|---|---|---|
| lint | passed | 0.0s |
| test | passed | 0.0s |
| package | passed | 0.0s |
Next, a regression: the line in slugify that removes a trailing hyphen was changed so that it only removes a leading one. The test stage caught it, produced an error annotation, and the pipeline stopped before packaging:
::group::Stage: lint
checked 1 commands and 3 scripts, 0 with errors
::endgroup::
stage lint: passed (0.0s)
::group::Stage: test
ok - 'Hello World'
FAIL - ' Bash & CI/CD ': expected 'bash-ci-cd', got 'bash-ci-cd-'
ok - 'Already-a-slug'
ok - 'Version 2.0'
::error file=tests/test_slug.sh,line=1::1 test file(s) failed: tests/test_slug.sh
::endgroup::
stage test: FAILED (0.0s)
[status 1]
A syntax error, an if without its fi in lib/slug.sh, was caught by the lint stage, with the line that bash -n reported:
::group::Stage: lint
::error file=lib/slug.sh,line=9::syntax error near unexpected token `}'
checked 1 commands and 3 scripts, 1 with errors
::endgroup::
stage lint: FAILED (0.0s)
[status 1]
Bash reports the line where it noticed the problem, the closing } of the function, which is not always the line with the mistake. In GitLab mode, cat -v makes the section markers visible (^[ is the escape character and ^M the carriage return), and the outputs go to the dotenv file:
$ GITLAB_CI=true ci/run.sh lint | cat -v
^[[0Ksection_start:1796099411:lint[collapsed=true]^M^[[0KStage: lint
checked 1 commands and 3 scripts, 0 with errors
^[[0Ksection_end:1796099411:lint^M^[[0K
stage lint: passed (0.0s)
$ GITLAB_CI=true ci/run.sh package > /dev/null; cat ci-outputs.env
version=v1.4.0-4-gdd8884c
artifact=dist/slug-v1.4.0-4-gdd8884c.tar.gz
$ ci/run.sh deploy
unknown stage: deploy
[status 2]
The CI Configuration
With the logic in the script, the configuration files stay short. A GitHub Actions workflow:
name: ci
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history and tags, for git describe
- id: pipeline
run: ci/run.sh
- uses: actions/upload-artifact@v4
with:
name: slug-${{ steps.pipeline.outputs.version }}
path: dist/
and the equivalent GitLab CI job:
build:
image: debian:stable
variables:
GIT_DEPTH: 0 # full history and tags, for git describe
before_script:
- apt-get update && apt-get install -y --no-install-recommends git
script:
- ci/run.sh
artifacts:
paths: [dist/]
reports:
dotenv: ci-outputs.env
Both set the clone depth to the full history. CI systems clone only the most recent commits by default to save time; in such a shallow clone, git describe finds no tags and falls back to the bare commit hash:
$ git clone -q --depth 1 file:///path/to/proj shallow && cd shallow && git describe --tags --always --dirty
dd8884c
The workflow then uses the step output version, written through GITHUB_OUTPUT, to name the uploaded artifact. In GitLab, later jobs receive version and artifact as variables through the dotenv report.