Using Bash in CI/CD Pipelines

Su Suriya Ravichandran Updated 06 Dec 2026
17 min read ·Lesson 177 of 205

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:

  1. The exit status decides the result. A step passes when its script exits with 0 and fails otherwise. Output such as ERROR in the log does not fail a step; only the exit status does.
  2. The shell options come from the CI system. In GitHub Actions, shell: bash runs the script as bash --noprofile --norc -eo pipefail {0}, while a step without a shell: setting on a Linux runner runs as bash -e {0}. {0} stands for the temporary script file.
  3. 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.sh or scripts/test.sh with 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:

PurposeGitHub ActionsGitLab CI
running in CI at allCI=trueCI=true
which systemGITHUB_ACTIONS=trueGITLAB_CI=true
commit being builtGITHUB_SHACI_COMMIT_SHA
branch or tag nameGITHUB_REF_NAMECI_COMMIT_REF_NAME
repository checkoutGITHUB_WORKSPACECI_PROJECT_DIR
run identifierGITHUB_RUN_IDCI_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:

VariableWhat appending to the file does
GITHUB_OUTPUTname=value lines become outputs of the step, read later as steps.<id>.outputs.name
GITHUB_ENVNAME=value lines become environment variables in all later steps of the job
GITHUB_PATHeach line is a directory added to PATH for later steps
GITHUB_STEP_SUMMARYMarkdown 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 pipefail makes the script independent of the options the CI system uses, and cd "$(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, so ci/run.sh deploy fails with a clear message instead of a "command not found" error. Calling "stage_$stage" inside if is deliberate: in the condition of an if, set -e is disabled, so a failing stage is recorded as FAILED instead 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 form FILE: line N: MESSAGE; two sed expressions 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 bash process, collects the failures, and reports them all before failing.
  • Package names the archive after git describe --tags --always --dirty, which produces versions such as v1.4.0-4-gdd8884c (four commits after tag v1.4.0, at commit dd8884c), adds -dirty when tracked files have uncommitted changes, and falls back to the commit hash when there are no tags. The checksum is created from inside dist, so the .sha256 file contains just the file name and can be checked later with sha256sum -c.
  • Timing without external tools. $EPOCHREALTIME contains the time with microseconds, such as 1796099411.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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Using Bash in CI/CD Pipelines and get answers drawn from it.

Signed-in readers only.