How to Delete a Git Branch Locally and Remotely (Step-by-Step)

Quick answer:

git branch -d branch_name          # delete local branch
git push origin --delete branch_name   # delete remote branch
Diagram showing local branch, remote-tracking branch, and remote branch as three separate things in Git

Why deleting a branch feels confusing

Most people expect one "branch" per name, but Git actually tracks three separate things: your local branch, your local remote-tracking branch (e.g. origin/feature), and the branch that actually lives on the remote server. Deleting one doesn't automatically delete the others.

Step 1: Delete the local branch

git branch -d branch_name
# or, to force-delete an unmerged branch:
git branch -D branch_name

Step 2: Delete the remote branch

git push origin --delete branch_name

Older Git versions or scripts sometimes use the equivalent long form:

git push origin :branch_name

Step 3: Clean up stale remote-tracking references

If a teammate deleted the remote branch, your local clone may still show it under git branch -r. Prune it with:

git fetch --prune
# or, to prune on every fetch automatically:
git config --global fetch.prune true

FAQ

Why does git branch -d fail with "not fully merged"?

Git is protecting you from losing commits that exist only on that branch. If you're sure you don't need them, use -D instead of -d.

Do I need to delete the local and remote branch in a specific order?

No, they're independent operations and can be done in either order, or just one of them if that's all you need.

How do I delete a branch on GitHub without the command line?

GitHub automatically offers a "Delete branch" button after a pull request is merged, which is equivalent to git push origin --delete.


This article explains and expands on the community answers to the Stack Overflow question “How do I delete a Git branch locally and remotely?”, used under the CC BY-SA 4.0 license. Screenshot credit: Stack Exchange Inc.

No comments

Post a Comment