Delete old branches (local and on GitHub)
careful beginner #branch#cleanup#delete#prune
When to use this: Finished branches are piling up and you want to clean up.
Be careful with this one.
-D deletes a branch even if its work was never merged. Prefer -d, which refuses. Before you start
Steps
-
See merged branches
terminalgit branch --merged mainLists local branches whose work is already in
main. Those are safe to delete. -
Delete a local branch (safe)
terminalgit branch -d my-branchGit refuses if the branch has unmerged commits, which protects you.
-
Delete it on GitHub
terminalgit push origin --delete my-branchRemoves the remote branch. GitHub also offers a 'Delete branch' button after merging a PR.
-
Forget remote branches that no longer exist
terminalgit fetch --pruneRemoves stale
origin/<name>entries that were deleted on GitHub.
How to verify it worked
git branch -ano longer lists the branch.
How to undo it
Deleted the wrong branch? Its commits still exist for a while. Find the last commit ID and recreate it:
terminal
git reflog
git branch my-branch <commit-id>Common errors and fixes
error: The branch 'x' is not fully merged It has commits that are not in your current branch. Merge it first, or if you truly want to discard it use git branch -D x. Cannot delete branch 'x' checked out at ... Switch to another branch first. Q&A
Does deleting a branch delete its commits?
Only the label goes away. The commits stay reachable through the reflog for a time, and forever if another branch contains them.