Need to delete a branch in GitHub? It’s a simple operation and keeping your repo clean & tidy is incredibly important in any project. In this post, I’ll show you how to:
- Delete a local git branch.
- Delete a remote git branch.
- Delete merged git branches.
- Delete all local branches except master.
- Recover a deleted git branch.
Delete a Local GitHub Branch
$ git branch -d yourbranch Deleted branch yourbranch (was 2a4ef7)
Depending if you already have unmerged commits in the branch you’re trying to delete, you may see this error:
error: The branch 'my-branch' is not fully merged. If you are sure you want to delete it, run 'git branch -D my-branch'.
This protects you from losing your reference to those commits, which means you would effectively lose access to that entire line of development. If you really want to delete the branch (e.g., it’s a failed experiment), you can use the capital -D flag:
$ git branch -D yourbranch Deleted branch yourbranch (was 2a4ef7)
This is the command to use if you want to permanently throw away all of the commits associated with a particular line of development.
Delete a Remote GitHub Branch
As of Git v1.7.0, you can delete a remote branch using:
$ git push origin --delete yourbranch
Previous to Git v1.7.0, you can use:
$ git push origin :yourbranch
Delete Merged Branches
Through time as you create and merge branches, you’ll want to delete the one’s no longer needed. In order to delete local branches which have already been merged, run:
$ git branch --merged master | grep -v "\*master" | xargs -n 1 git branch -d
You can omit the master branch argument to remove local branches which have already been merged into the current HEAD:
$ git branch --merged | grep -v "\*" | xargs -n 1 git branch -d
For more information, see Git Clean: Delete Already-Merged Branches.
Delete All Branches Except Master
If you’re like me, you leave branches laying around, even after they’ve been merged into
master. The sad part is GitHub even provides a button to do the cleanup, but I can’t be bothered. So when you’re ready to do some real cleanup on a repository, run this command to delete every branch in your local except for the
git branch | grep -v "master" | sed 's/^[ *]*//' | sed 's/^/git branch -d /' | bash
Recover a Deleted GitHub Branch
What if you accidentally deleted a branch or just need to recover one that’s been deleted? Not a problem. Use the following to find the HEAD commit of the deleted branch to get it back:
$ git fsck --full --no-reflogs | grep commit dangling commit 609bb956bc9ef1b43c0w6af60fa009e37be0566d dangling commit 608bb956bc9ef1b43c0g4af60fa0e9e34be0566d dangling commit 708bb956bc9ef1b43c0wdaf60fa000e99be0566d dangling commit 402bb956bc9ef1b43c0d4af60fa001e87be0566d
Then do a
git show to find the commit you want to recover:
git show 609bb956bc9ef1b43c0w6af60fa009e37be0566d
Once you found the commit you want, do a
git branch to recover the branch:
git branch 609bb956bc9ef1b43c0w6af60fa009e37be0566d