Remove local branches that have been merged into main and prune stale remote-tracking refs.
You are removing local branches that have already been merged into main. This is a safe, non-destructive cleanup. Follow every step in order. Show each command before running it.
Run:
git branch --merged main
This shows all local branches whose commits are fully contained in main — meaning they are safe to delete.
From the output of Step 1, remove the following branches — these must never be deleted:
mainmasterThe remaining branches are candidates for deletion. Store as {branches_to_delete}.
If {branches_to_delete} is empty:
If there are branches to delete, show them:
The following merged branches will be deleted:
{list each branch on its own line}
Ask: "Delete these branches? (yes/no)"
For each branch in {branches_to_delete}, run:
git branch -d {branch}
Use -d (safe delete), not -D (force delete). The -d flag will refuse to delete a branch that has unmerged changes, which is a safety net.
If any deletion fails with an error, report it and continue with the rest of the list. Do not stop the entire cleanup for one failure.
Keep a count of:
Fetch and prune stale remote-tracking references (refs to remote branches that no longer exist on GitHub):
git fetch --prune
This cleans up entries like origin/feat/old_branch that remain locally after the remote branch is deleted on GitHub.
Print a summary:
Branch cleanup complete.
Deleted: {count} branch(es)
Pruned: remote-tracking refs updated
If any branches failed to delete:
Skipped: {count} branch(es) (see details above)
List the successfully deleted branch names and any that were skipped with their reasons.