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:
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 test/slugify.test.shThree 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.
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"
SHHow the filters behave:
paths-ignoreskips the workflow when every changed file matches one of its patterns. A pull request that touchesdocs/setup.mdandsrc/slugify.shstill runs the tests, because one file is not ignored.pathsis the opposite: the workflow runs when at least one changed file matches. The docs check ignores code-only changes.**.mdmatches a Markdown file at any depth, including the rootREADME.md.docs/**matches everything underdocs/.- You cannot use
pathsandpaths-ignorefor the same event. To include a folder but leave out part of it, usepathswith 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 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:
- A small
changesjob lists the changed files withgit diff --name-onlyand sets an output,code, totrueorfalse. - The
testjob runs only whencodeistrue. - A
checks-passedjob 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 leftmain", so commits that landed onmainmeanwhile are not counted. - On a push, the event carries
github.event.before, the commit the branch pointed to before the push. The range isbefore..HEAD. When a branch is new,beforeis 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.
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
SHIn 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:
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 mainNow make a documentation-only change on a branch, and run the script both as a push and as a pull request would:
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.shThen change a code file on the same branch and run it again, plus the new-branch case:
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.shCheck 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:
git switch main
git branch -D docs-typoStep 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:
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
YAMLThe pieces that matter:
fetch-depth: 0makes the checkout fetch the whole history and every branch. The default is a single commit, andgit diffwould 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() }}makeschecks-passedrun even whentestfails or is skipped. Without it, a failedtestwould skipchecks-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 assuccess skipped. The gate passes onsuccessandskipped, and fails onfailureorcancelled. Ifchangesitself fails,testis skipped, but the gate still seesfailurefromchanges.timeout-minutesis on every job. The step about time limits explains why.
Check it worked
Run the gate with the results it will see on GitHub:
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:
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
YAMLHow the group name is built:
github.workflowis the workflow name,Test, so this group never collides with the deploy workflow's group.github.head_refis the pull request's branch name, and is only set on pull request events. On a push it is empty, so||falls back togithub.ref, such asrefs/heads/main. Each pull request and each branch gets its own group.cancel-in-progressistrueonly for pull requests. Pushing three fixes to a branch in a row leaves one run going instead of three. Onmainit isfalse, 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
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:
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
YAMLThree 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 throughworkflow_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: falsemeans a running deploy always finishes. A newer push waits for it.- The workflow-level
paths-ignoreis fine here, because nobody requires a deploy check on pull requests. A docs-only merge tomaindoes 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:
concurrency:
group: deploy-production
cancel-in-progress: false
queue: maxGitHub 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 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:
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:
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
YAMLThe docs workflow only runs on pull requests, so it cancels superseded runs unconditionally.
Check it worked
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:
git add .
git commit -m "Filter jobs by changed files, cancel stale runs, queue deploys, add timeouts"
git log --onelinePoint origin at your GitHub repository instead of the local practice remote, and push. Replace YOUR-USER/YOUR-REPO with your repository:
git remote set-url origin git@github.com:YOUR-USER/YOUR-REPO.git
git push -u origin mainOnce 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:
rm -rf ~/ci-filters-demo-origin.gitCheck 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-passedon 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
Related tutorials
- Run Python tests and linters in GitHub Actions with uvYou will have a GitHub Actions workflow that installs a Python project with uv from its lock file, fails on a stale uv.lock, runs Ruff and pytest with a coverage floor on two Python versions, caches uv's downloads and keeps the coverage report as an artifact.
- Publish an npm package from GitHub Actions with trusted publishing and provenanceYou will have a small npm package that GitHub Actions publishes on each version tag through npm trusted publishing, with no NPM_TOKEN secret and a provenance attestation on every release.
- Pass build artifacts and outputs between GitHub Actions jobsYou will have a GitHub Actions workflow that builds a dist/ folder once, tests and deploys those exact files in later jobs, passes the version and a checksum between jobs as outputs, and writes a build summary, with every script checked on your own machine first.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials