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

  1. See merged branches

    terminal
    git branch --merged main

    Lists local branches whose work is already in main. Those are safe to delete.

  2. Delete a local branch (safe)

    terminal
    git branch -d my-branch

    Git refuses if the branch has unmerged commits, which protects you.

  3. Delete it on GitHub

    terminal
    git push origin --delete my-branch

    Removes the remote branch. GitHub also offers a 'Delete branch' button after merging a PR.

  4. Forget remote branches that no longer exist

    terminal
    git fetch --prune

    Removes stale origin/<name> entries that were deleted on GitHub.

How to verify it worked

  • git branch -a no 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.

Practice these as flashcards →

Terms in this scenario

Related scenarios

My notes

Saved in this browser only.