How to Run a Nightly Cleanup of Stale Branches in GitHub Actions
A nightly scheduled job can list merged branches with the gh CLI and delete the ones past a cutoff.
Run on schedule, then use the gh CLI (preinstalled on runners) to find branches merged into the default branch and delete them, skipping protected ones.
Steps
- Trigger the workflow on a nightly
cron. - Grant
contents: writeso the job can delete refs. - Use
gh apiorgit branch --mergedto find candidates, then delete them.
Workflow
.github/workflows/ci.yml
on:
schedule:
- cron: '0 2 * * *'
permissions:
contents: write
jobs:
prune:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- run: |
for b in $(git branch -r --merged origin/main | grep -v 'origin/main' | sed 's|origin/||'); do
git push origin --delete "$b" || true
done
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}Gotchas
- Protected branches reject deletion; the
|| truekeeps the loop going. - Test with a dry run first so you do not delete an active branch by mistake.
Related guides
How to Schedule Cleanup of Old Artifacts in GitHub ActionsDelete artifacts past a cutoff on a nightly GitHub Actions schedule using the REST API through the gh CLI, re…
How to Run a Workflow on a Cron Schedule in GitHub ActionsTrigger a GitHub Actions workflow on a recurring timetable with on.schedule and a five-field POSIX cron expre…