How to Delete a Git Branch

Delete a local Git branch safely or by force, remove the matching branch on the remote, prune stale tracking refs, and recover a branch deleted by mistake.

A feature branch has been merged and you want it gone, locally and on the remote. Git will not delete the branch you are standing on, so switch off it first.

Switch to another branch

git switch main

Git refuses to delete the current branch, so move to main (or any other branch) before continuing.

Delete the local branch

git branch -d feature
Deleted branch feature (was 3f2a1c9).

Lowercase -d is the safe option: it only deletes the branch if its commits are already merged into the current branch or its upstream. Otherwise it stops:

error: the branch 'feature' is not fully merged

Force-delete if the work is unwanted

git branch -D feature

Uppercase -D deletes the branch whether or not it is merged. Any commits that exist only on that branch become unreachable, so use it when you are sure the work should be thrown away.

Delete the branch on the remote

git push origin --delete feature
To github.com:user/repo.git
 - [deleted]         feature

This removes feature from the remote and drops your origin/feature tracking ref in the same step. Deleting a local branch never touches the remote, and deleting the remote branch never touches other people's local copies.

Clean up stale remote-tracking branches

When someone else deletes a branch on the remote, your origin/feature ref stays until you prune:

git fetch --prune
From github.com:user/repo
 - [deleted]         (none)     -> origin/feature

To make this automatic on every fetch and pull: git config --global fetch.prune true.

git branch -a lists local and remote-tracking branches, and git branch --merged shows local branches already merged into the current one, which is a quick way to find candidates for deletion.

If you deleted the wrong branch. The commits are still in the repository; Git keeps unreachable commits for at least 30 days by default. Find the branch tip with git reflog (look for the last commit made on it, or use the hash from the "Deleted branch feature (was 3f2a1c9)" message printed at deletion time), then recreate it: git branch feature 3f2a1c9. If the branch was also deleted on the remote, push it again with git push -u origin feature.

More Coding how-tos