GitHub Actions: avoid double runs from on: [push, pull_request]

I’ve often seen a GitHub Actions workflow defined with a trigger like:
on: [push, pull_request]
This means “run on any push or when a pull request is opened or updated”. While that may seem correct, it leads to double execution of the workflow when you push a commit and then create a pull request with it. You can see this in the status check details for the pull request:

Double execution means double the cost, extra waiting time, and increased chance of a spurious/flaky failure.
A better on clause looks like:
on:
push:
branches:
- main
pull_request:
This means “run for any push to the main branch or when a pull request is opened or updated”. If your workflow should run for tagged pushes as well, use:
on:
push:
branches:
- main
tags:
- '**'
pull_request:
This might be useful when your workflow contains a release job, as my open source projects do (example).
You’ll then see just a single run for your workflow in pull requests, like:

😸😸😸 Check out my new book on using GitHub effectively, Boost Your GitHub DX! 😸😸😸
One summary email a week, no spam, I pinky promise.
Related posts:
- GitHub Actions: Faster Python runs with cached virtual environments
- GitHub: render GitHub-Flavored Markdown with the API
Tags: github