Git Prune Branches (Both Local and Remote)
Check and prune both local and remote branches that have been merged:
Step 1: Prune Local Branches
- Get the list of all local branches using
git branch - For each branch, check if it has been merged using
git branch --merged - Exclude protected branches (main, master, develop, etc.)
- Create a list of local branches that are safe to delete
Step 2: Prune Remote Branches
- Fetch the latest remote information using
git fetch --prune - Get the list of all remote branches using
git branch -r - For each remote branch, check if it has been merged into the remote main branch
- Exclude protected branches
- Create a list of remote branches that are safe to delete
Step 3: Confirm and Execute
- Present both lists to the user clearly:
- Local branches to be deleted
- Remote branches to be deleted
- Ask for confirmation: "The above local and remote branches will be deleted. Proceed? (yes/no)"
- If user confirms with "yes" or similar affirmative response:
- Delete local branches using
git branch -d <branch-name> - Delete remote branches using
git push origin --delete <branch-name>
- Report the results for both operations
Important: Never delete:
- The currently checked out branch (for local)
- Protected branches: main, master, develop, development, staging, production
- Branches that are not fully merged (unless explicitly requested)
Note: Remote deletion affects the repository for all users and cannot be easily undone. Ensure user confirmation before proceeding.