Skip to main content

CI/CD and automation · Intermediate · 18 min

Run only the CI jobs a change needs with path filters and concurrency

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · GitHub Actions · Git · actionlint 1.7.12

You will have GitHub Actions workflows that skip tests for documentation-only changes without blocking merges, cancel superseded pull request runs, queue deploys instead of cancelling them, and stop any job that runs too long.

On this page

Every push to a busy repository starts the same workflows, whether it changes the payment code or fixes a typo in a README. That costs runner minutes, and it costs attention: three quick pushes to a pull request leave three test runs going, and only the last one matters. Worse, a deploy job that hangs can hold a runner for six hours before GitHub gives up on it.

In this tutorial you tighten that up in a small repository. You start with the obvious tool, workflow-level paths-ignore, and see why it breaks merges when the workflow is a required check. Then you replace it with a short Bash script that decides inside the workflow whether code changed, so the required check always reports a result. You add a concurrency group that cancels outdated pull request runs, a separate one that never cancels a deploy, and a time limit on every job. Every script runs on your machine first, and actionlint checks every workflow before it goes near GitHub.

Step 1 · Build a small repository with code, docs and a test

The project is a Bash script that turns a title into a URL slug, a test for it, and a docs/ folder. That is enough to have two kinds of change: ones that can break the code and ones that cannot. Create it in a throwaway folder:

Bash
mkdir -p ~/ci-filters-demo
cd ~/ci-filters-demo
git init -b main
mkdir -p src test docs ci .github/workflows

cat > src/slugify.sh <<'SH'
#!/usr/bin/env bash
# Turns a title into a URL slug: "Hello, World" becomes "hello-world".
set -euo pipefail
printf '%s\n' "$*" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+//; s/-+$//'
SH

cat > test/slugify.test.sh <<'SH'
#!/usr/bin/env bash
# Runs src/slugify.sh on known titles and compares the result.
set -euo pipefail
failed=0
check() {
  local got
  got="$(bash src/slugify.sh "$1")"
  if [ "$got" = "$2" ]; then
    echo "ok: '$1' -> '$got'"
  else
    echo "FAIL: '$1' gave '$got', expected '$2'"
    failed=1
  fi
}
check "Hello, World" "hello-world"
check "  CI/CD in 2026  " "ci-cd-in-2026"
check "Already-a-slug" "already-a-slug"
exit "$failed"
SH

cat > docs/setup.md <<'MD'
# Setting up

Clone the repository and run the tests.
MD

cat > README.md <<'MD'
# ci-filters-demo

Turns titles into URL slugs.
MD

git add .
git commit -m "Add slugify script, test and docs"

Check it worked

Bash
bash test/slugify.test.sh

Three lines start with ok: and the command exits without an error. git log --oneline shows one commit.

Step 2 · Skip whole workflows with paths and paths-ignore

GitHub can decide before a workflow starts whether it should run at all, by comparing the changed files with the patterns under on.<event>.paths or paths-ignore. Add two workflows: tests that ignore documentation, and a docs check that runs only when documentation changes.

Bash
cat > .github/workflows/test.yml <<'YAML'
name: Test

on:
  push:
    branches: [main]
    paths-ignore:
      - 'docs/**'
      - '**.md'
  pull_request:
    paths-ignore:
      - 'docs/**'
      - '**.md'

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: bash test/slugify.test.sh
YAML

cat > .github/workflows/docs.yml <<'YAML'
name: Docs

on:
  pull_request:
    paths:
      - 'docs/**'
      - '**.md'

permissions:
  contents: read

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: bash ci/check-docs.sh
YAML

cat > ci/check-docs.sh <<'SH'
#!/usr/bin/env bash
# Fails if a Markdown file in docs/ does not start with a "# " heading.
set -euo pipefail
status=0
for file in docs/*.md; do
  if head -n 1 "$file" | grep -q '^# '; then
    echo "ok: $file"
  else
    echo "no top heading: $file"
    status=1
  fi
done
exit "$status"
SH

How the filters behave:

  • paths-ignore skips the workflow when every changed file matches one of its patterns. A pull request that touches docs/setup.md and src/slugify.sh still runs the tests, because one file is not ignored.
  • paths is the opposite: the workflow runs when at least one changed file matches. The docs check ignores code-only changes.
  • **.md matches a Markdown file at any depth, including the root README.md. docs/** matches everything under docs/.
  • You cannot use paths and paths-ignore for the same event. To include a folder but leave out part of it, use paths with a pattern that starts with !, such as '!docs/drafts/**' after 'docs/**'.
  • If a push or pull request changes more than 3,000 files, GitHub may not see every file when it applies the filter, so a very large change can behave unexpectedly.

Check it worked

Bash
bash ci/check-docs.sh
actionlint
echo "actionlint exit code: $?"

The docs check prints ok: docs/setup.md. actionlint prints nothing and the exit code is 0.

Step 3 · See why a skipped workflow blocks a required check

Workflow-level filters are fine for the docs check, because nobody requires it. The test workflow is different. Most teams protect main with a rule that requires the test check to pass before a pull request can merge.

Now open a pull request that only fixes a typo in docs/setup.md. The test workflow is skipped before it starts, so no test check is ever created. GitHub does not treat a check that never reported as a pass: it waits for it, the pull request shows the check as expected and pending, and the merge button stays blocked. GitHub's own advice is to avoid requiring workflows that can be skipped this way.

A job is a different matter. When a workflow runs but one of its jobs is skipped because its if: condition is false, that job reports its status as Success, which satisfies a required check. So the fix is to let the workflow always start and to make the skip decision inside it:

  1. A small changes job lists the changed files with git diff --name-only and sets an output, code, to true or false.
  2. The test job runs only when code is true.
  3. A checks-passed job always runs, looks at how the other jobs ended, and is the one check you require.

The script for the first job needs to know what to compare against:

  • On a pull request, the comparison is the base branch: origin/main...HEAD. The three dots mean "changes on this branch since it left main", so commits that landed on main meanwhile are not counted.
  • On a push, the event carries github.event.before, the commit the branch pointed to before the push. The range is before..HEAD. When a branch is new, before is all zeros, and after a force push the old commit may not be in the clone; in both cases there is nothing sensible to compare with, so the script runs everything.

Check it worked

Write down, for your own repository, which folders hold code that the tests depend on and which hold only documentation or other files. For this project, everything is code except docs/, Markdown files and LICENSE. That list becomes the case pattern in the next step.

Step 4 · Write a change filter script and test it locally

Write the script. It reads three environment variables that the workflow will set, EVENT_NAME, BASE_REF and BEFORE, and prints code=true or code=false. When GITHUB_OUTPUT is set, as it is in a workflow step, it also writes the result there so later jobs can read it.

Bash
cat > ci/changes.sh <<'SH'
#!/usr/bin/env bash
# Decides whether a push or pull request touches code. Prints code=true or code=false
# and, in a workflow, saves it as the step output "code".
set -euo pipefail

zeros=0000000000000000000000000000000000000000
range=""
case "${EVENT_NAME:-push}" in
  pull_request)
    range="origin/${BASE_REF:?BASE_REF is not set}...HEAD"
    ;;
  *)
    if [ -n "${BEFORE:-}" ] && [ "$BEFORE" != "$zeros" ] && git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then
      range="$BEFORE..HEAD"
    fi
    ;;
esac

code=true
if [ -n "$range" ]; then
  files="$(git diff --name-only "$range")"
  printf 'Changed files in %s:\n%s\n' "$range" "${files:-(none)}"
  code=false
  while IFS= read -r file; do
    [ -z "$file" ] && continue
    case "$file" in
      docs/*|*.md|LICENSE) ;;
      *) code=true; break ;;
    esac
  done <<EOF
$files
EOF
else
  echo "No earlier commit to compare with, so treating this as a code change."
fi

echo "code=$code"
if [ -n "${GITHUB_OUTPUT:-}" ]; then
  echo "code=$code" >> "$GITHUB_OUTPUT"
fi
SH

In a case pattern, * also matches /, so docs/* covers files in subfolders of docs/ and *.md covers Markdown anywhere. When in doubt the script says true: running the tests needlessly costs a few minutes, while skipping them wrongly lets a bug through.

Commit the work so far, and push it to a local bare repository that stands in for GitHub, so origin/main exists the way it will in a workflow:

Bash
git add .
git commit -m "Add workflows, docs check and change filter"
git init --bare ~/ci-filters-demo-origin.git
git remote add origin ~/ci-filters-demo-origin.git
git push -u origin main

Now make a documentation-only change on a branch, and run the script both as a push and as a pull request would:

Bash
git switch -c docs-typo
echo "Run the tests with: bash test/slugify.test.sh" >> docs/setup.md
git commit -am "Explain how to run the tests"

EVENT_NAME=push BEFORE="$(git rev-parse HEAD~1)" bash ci/changes.sh
EVENT_NAME=pull_request BASE_REF=main bash ci/changes.sh

Then change a code file on the same branch and run it again, plus the new-branch case:

Bash
printf '\n# Slugs contain only a-z, 0-9 and hyphens.\n' >> src/slugify.sh
git commit -am "Document the slug alphabet"

EVENT_NAME=push BEFORE="$(git rev-parse HEAD~1)" bash ci/changes.sh
EVENT_NAME=pull_request BASE_REF=main bash ci/changes.sh
EVENT_NAME=push BEFORE=0000000000000000000000000000000000000000 bash ci/changes.sh

Check it worked

The first pair of runs lists only docs/setup.md and ends with code=false. After the code change, the push run lists src/slugify.sh and ends with code=true, and the pull request run lists both files, because it looks at the whole branch, and also ends with code=true. The all-zeros run prints the "No earlier commit" message and code=true.

Go back to main and drop the practice branch:

Bash
git switch main
git branch -D docs-typo

Step 5 · Run the filter as a job and add a check that always reports

Replace the test workflow. The workflow-level filters go, and three jobs take their place:

Bash
cat > ci/gate.sh <<'SH'
#!/usr/bin/env bash
# Passes only if every needed job succeeded or was skipped on purpose.
set -euo pipefail
echo "Needed job results: ${RESULTS:?RESULTS is not set}"
for result in $RESULTS; do
  case "$result" in
    success|skipped) ;;
    *) echo "A needed job ended with: $result"; exit 1 ;;
  esac
done
echo "All needed jobs passed or were skipped."
SH

cat > .github/workflows/test.yml <<'YAML'
name: Test

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

jobs:
  changes:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    outputs:
      code: ${{ steps.filter.outputs.code }}
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
      - id: filter
        env:
          EVENT_NAME: ${{ github.event_name }}
          BASE_REF: ${{ github.base_ref }}
          BEFORE: ${{ github.event.before }}
        run: bash ci/changes.sh

  test:
    needs: changes
    if: needs.changes.outputs.code == 'true'
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v7
      - run: bash test/slugify.test.sh

  checks-passed:
    if: ${{ !cancelled() }}
    needs: [changes, test]
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v7
      - name: Check how the needed jobs ended
        env:
          RESULTS: ${{ join(needs.*.result, ' ') }}
        run: bash ci/gate.sh
YAML

The pieces that matter:

  • fetch-depth: 0 makes the checkout fetch the whole history and every branch. The default is a single commit, and git diff would have nothing to compare with.
  • The event values reach the script through env: rather than being pasted into the command with ${{ }}, which keeps branch names out of the shell's parsing.
  • if: ${{ !cancelled() }} makes checks-passed run even when test fails or is skipped. Without it, a failed test would skip checks-passed, and a skipped job counts as a success, which is exactly wrong here. The one case it skips the gate is when the whole run is cancelled, such as a superseded pull request run in the next step; the newer run then reports the check instead. The braces are needed because YAML would otherwise read the leading ! as a tag.
  • join(needs.*.result, ' ') gives a string such as success skipped. The gate passes on success and skipped, and fails on failure or cancelled. If changes itself fails, test is skipped, but the gate still sees failure from changes.
  • timeout-minutes is on every job. The step about time limits explains why.

Check it worked

Run the gate with the results it will see on GitHub:

Bash
RESULTS="success skipped" bash ci/gate.sh
RESULTS="success failure" bash ci/gate.sh || echo "The gate failed, as it should (exit code $?)"
actionlint
echo "actionlint exit code: $?"

The first run ends with All needed jobs passed or were skipped. The second prints A needed job ended with: failure and then the line from echo. actionlint exits with 0.

Step 6 · Cancel superseded runs with a concurrency group

A concurrency group is a name. GitHub lets only one run with that name be in progress at a time. With cancel-in-progress: true, a new run in the group cancels the one already running. Add one to the test workflow, after permissions:

Bash
cat > .github/workflows/test.yml <<'YAML'
name: Test

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

jobs:
  changes:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    outputs:
      code: ${{ steps.filter.outputs.code }}
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
      - id: filter
        env:
          EVENT_NAME: ${{ github.event_name }}
          BASE_REF: ${{ github.base_ref }}
          BEFORE: ${{ github.event.before }}
        run: bash ci/changes.sh

  test:
    needs: changes
    if: needs.changes.outputs.code == 'true'
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v7
      - run: bash test/slugify.test.sh

  checks-passed:
    if: ${{ !cancelled() }}
    needs: [changes, test]
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v7
      - name: Check how the needed jobs ended
        env:
          RESULTS: ${{ join(needs.*.result, ' ') }}
        run: bash ci/gate.sh
YAML

How the group name is built:

  • github.workflow is the workflow name, Test, so this group never collides with the deploy workflow's group.
  • github.head_ref is the pull request's branch name, and is only set on pull request events. On a push it is empty, so || falls back to github.ref, such as refs/heads/main. Each pull request and each branch gets its own group.
  • cancel-in-progress is true only for pull requests. Pushing three fixes to a branch in a row leaves one run going instead of three. On main it is false, so every merged commit gets a finished result you can look back on.

Even with cancel-in-progress: false, a group holds at most one waiting run by default. If a run is in progress and two more arrive, the first of the two waiting runs is cancelled and the newest takes its place. That is usually what you want on main: the newest commit contains the others.

On private repositories, cancelled runs are minutes you are not billed for. If your team works from a limited monthly allowance of Actions minutes, cancelling superseded pull request runs is one of the cheapest ways to make it last.

Check it worked

Bash
actionlint
echo "actionlint exit code: $?"

Exit code 0. On GitHub, push two commits to a pull request branch within a few seconds: the first run shows as cancelled, with a note along the lines of a higher priority run in the same group having cancelled it, and the second runs to the end.

Step 7 · Queue deploys instead of cancelling them

Cancelling a test run is harmless. Cancelling a deploy halfway can leave a server with half its new files, or a database migration partly applied. A deploy workflow wants the opposite setting: one deploy at a time, never cancelled once started. Add a deploy workflow and the script it calls:

Bash
cat > ci/deploy.sh <<'SH'
#!/usr/bin/env bash
# Stand-in deploy step. Replace the echo with your own deploy commands.
set -euo pipefail
echo "Deploying commit ${GITHUB_SHA:-$(git rev-parse HEAD)}"
SH

cat > .github/workflows/deploy.yml <<'YAML'
name: Deploy

on:
  push:
    branches: [main]
    paths-ignore:
      - 'docs/**'
      - '**.md'
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: deploy-production
  cancel-in-progress: false

jobs:
  deploy:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v7
      - run: bash ci/deploy.sh
YAML

Three choices here:

  • The group name, deploy-production, is a fixed string rather than one built from the branch. Every deploy to production shares it, including one started by hand from the Actions tab through workflow_dispatch. If you add a second workflow that deploys to the same place, give it the same group name, so the two cannot run at once.
  • cancel-in-progress: false means a running deploy always finishes. A newer push waits for it.
  • The workflow-level paths-ignore is fine here, because nobody requires a deploy check on pull requests. A docs-only merge to main does not redeploy.

As in the previous step, only one deploy waits at a time: if three merges land during one deploy, the middle one is never deployed on its own, and the newest one, which contains it, goes out next. If you need every commit deployed in turn, set queue: max on the group. The default, queue: single, keeps one waiting run; max keeps up to 100 pending runs and starts them in order:

YAML
concurrency:
  group: deploy-production
  cancel-in-progress: false
  queue: max

GitHub rejects queue: max together with cancel-in-progress: true as a validation error, which makes sense: a queue that cancels its running job would never keep anything. This tutorial leaves queue out of the file you lint, because older linters may not know the key yet; run actionlint on your own copy before you push it.

Check it worked

Bash
bash ci/deploy.sh
actionlint
echo "actionlint exit code: $?"

The script prints Deploying commit followed by your latest commit hash, and actionlint exits with 0. On GitHub, merging two pull requests in quick succession shows the second deploy as pending until the first finishes; it is not cancelled.

Step 8 · Put a time limit on every job

A job without timeout-minutes runs for up to 360 minutes before GitHub cancels it. A test that waits forever on a network call, or a deploy stuck at a prompt, holds a runner for six hours. Set a limit a few times longer than the job normally takes.

The test and deploy workflows already have limits. A small script finds jobs that do not. It counts runs-on: and timeout-minutes: lines at job level, which in these files are indented by four spaces, so keep that layout if you use it:

Bash
cat > ci/check-timeouts.sh <<'SH'
#!/usr/bin/env bash
# Fails if a workflow has a job without timeout-minutes (jobs indented by four spaces).
set -euo pipefail
status=0
for file in .github/workflows/*.yml; do
  jobs="$(grep -cE '^    runs-on:' "$file" || true)"
  timeouts="$(grep -cE '^    timeout-minutes:' "$file" || true)"
  if [ "$jobs" = "$timeouts" ]; then
    echo "ok: $file ($jobs jobs)"
  else
    echo "missing timeout-minutes: $file has $jobs jobs and $timeouts limits"
    status=1
  fi
done
exit "$status"
SH

bash ci/check-timeouts.sh || echo "Some jobs have no time limit (exit code $?)"

The docs workflow from the second step has no limit, and the script says so. Rewrite it with one:

Bash
cat > .github/workflows/docs.yml <<'YAML'
name: Docs

on:
  pull_request:
    paths:
      - 'docs/**'
      - '**.md'

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
  cancel-in-progress: true

jobs:
  check:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v7
      - run: bash ci/check-docs.sh
YAML

The docs workflow only runs on pull requests, so it cancels superseded runs unconditionally.

Check it worked

Bash
bash ci/check-timeouts.sh
actionlint
echo "actionlint exit code: $?"

The script prints an ok: line for each of the three workflow files and exits with 0, and so does actionlint. You can call bash ci/check-timeouts.sh from the changes job later, so a new job without a limit fails review.

Step 9 · Push to GitHub and require the gate check

Commit the finished workflows:

Bash
git add .
git commit -m "Filter jobs by changed files, cancel stale runs, queue deploys, add timeouts"
git log --oneline

Point origin at your GitHub repository instead of the local practice remote, and push. Replace YOUR-USER/YOUR-REPO with your repository:

Bash
git remote set-url origin git@github.com:YOUR-USER/YOUR-REPO.git
git push -u origin main

Once the first run has finished, open your repository's rules for main and require the checks-passed status check. Do not require test: on documentation pull requests it is skipped, which reports as a success, but if you later rename or split it, a required test check that no longer exists blocks every merge. checks-passed is the one name that always appears. The rulesets tutorial covers the settings.

Delete the local practice remote when you no longer need it:

Bash
rm -rf ~/ci-filters-demo-origin.git

Check it worked

git log --oneline lists three commits on main. On GitHub, open a pull request that changes only docs/setup.md. In its checks list you see changes and checks-passed with green ticks, test marked as skipped, and the Docs workflow's check job. The merge button is available. Open a second pull request that changes src/slugify.sh: this time test runs, and checks-passed waits for it. Push a second commit to that branch straight away, and the first run shows as cancelled.

Next steps

  • Require checks-passed on main with a ruleset: /tutorials/block-merges-until-checks-pass-with-rulesets
  • Add a manual approval in front of the production deploy: /tutorials/require-approval-before-production-deploys-with-github-environments
  • Combine the change filter with a generated test matrix: /tutorials/run-a-build-matrix-across-operating-systems-and-versions
  • Lock down permissions and third-party actions in these workflows: /tutorials/harden-github-actions-workflows

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.