Automate Cleanup of Stale Merged Branches
Remove local and remote branches that have already been merged, keeping your repository clean and navigable.
Prerequisites
- -Git installed
- -A repository with multiple merged branches
- -Push access to the remote
Steps
Fetch and prune remote tracking branches
Sync with the remote and remove local references to branches that no longer exist on the remote.
Run this regularly or add it to your git config with `git config --global fetch.prune true` to auto-prune on every fetch.
List all merged local branches
Show local branches that have been fully merged into main. The grep excludes main, master, and the current branch.
Always verify the list before deleting. Some long-lived branches like release or develop may appear as merged.
Delete merged local branches
Pipe the merged branch list into xargs to delete each one. The -d flag only deletes fully merged branches, so it is safe.
The -r flag on xargs prevents an error when there are no branches to delete.
List merged remote branches
Show remote tracking branches that have been merged into main, stripping the origin/ prefix for readability.
Delete merged remote branches
Delete each merged remote branch. The -I {} placeholder passes each branch name to the push --delete command.
This is irreversible on the remote. Make sure no one else is working on these branches before deleting.
Verify cleanup results
List all remaining local and remote branches to confirm the stale ones have been removed.
Full Script
FAQ
Discussion
Loading comments...