How to Run a Step Only on the Main Branch in GitHub Actions
Check github.ref == 'refs/heads/main' in a step if to scope it to the default branch.
The github.ref context holds the full ref (e.g. refs/heads/main). Compare it in a step-level if to run only on main.
Steps
- Add
if: github.ref == 'refs/heads/main'to the step. - Use the full ref form, not the short branch name.
- Keep test steps unconditional so pull requests still run them.
Workflow
.github/workflows/ci.yml
steps:
- run: npm test
- name: Publish (main only)
if: github.ref == 'refs/heads/main'
run: npm publishGotchas
- On
pull_requesteventsgithub.refis the merge ref, so prefergithub.head_refthere. - Use
github.ref_nameif you want justmaininstead of the full ref.
Related guides
How to Gate a Deploy on the Branch With an if in GitHub ActionsPrevent a GitHub Actions deploy job from running off the wrong branch with a job-level if on github.ref, comb…
How to Run a Step Only When a Tag Is Pushed in GitHub ActionsRun a GitHub Actions step only for tag pushes by testing startsWith(github.ref, refs/tags/), ideal for releas…