While it's very common to need to create and delete branches in Git, unfortunately the syntax isn't very easy to remember for everyone. Even as a long-time user of Git I need to look up the syntax as a reminder, which admittedly is actually the main motivation behind writing this short article.
The next two sections will describe how to delete branches in Git, for both local and remote repositories, along with some alternative flags and syntax.
Deleting a Local Branch
This is the easy part since you're just working on the Git repository that you (presumably) own and control. Here is the command you'll likely need:
git branch -d <local_branch>
-d option tells Git to delete the branch specified, and is actually an alias for the
--delete flag. Another alternative is to use
-D instead, which forces the delete and is an alias for
git branch -D <local_branch>
This will delete the branch, even if it is not merged yet, so keep this in mind when using it. In general you should use the
-d option since it's considered safer.
Another thing to note - you can't delete the branch that branch that is currently checked out, even with the
-D option, which we show here with the
git checkout issue-260 Switched to branch 'issue-260' git branch -D issue-260 error: Cannot delete branch 'issue-260' checked out at '/Users/scott/projects/git-examples'
First, checkout a different branch, like
master or your dev branch, and then delete it:
git checkout master Switched to branch 'master' Your branch is up-to-date with 'origin/master'. git branch -d issue-260 Deleted branch issue-260 (was 3acde55).
Now we're able to delete the branch without issue.
Deleting a Remote Branch
Deleting a remote branch is slightly more involved than deleting a local one since you're working with a repository that is likely not even on your machine. The syntax you can use also depends on your version of Git, so take note.
git push <remote_repo> --delete <remote_branch>
This was added to Git in v1.7.0, and in Git v2.8.0 they added the ability to use
-d instead of the full
The format shown above, in my opinion, is the easiest syntax to remember. But if you have an older version of Git (v1.5.0+) then you'll need to use this instead:
git push <remote_repo> :<remote_branch>
To remember this, Scott Chacon puts it very well in his book:
A way to remember this command is by recalling the
git push [remotename] [localbranch]:[remotebranch]syntax that we went over a bit earlier. If you leave off the
[localbranch]portion, then you're basically saying, "Take nothing on my side and make it be
Now that the branch is gone from the remote repository, other machines will want to update themselves as well. To do this, they'll want to
fetch the update:
git fetch --all --prune
--prune option tells Git to remove all remote-tracking references (i.e. our branch) that no longer exist in the remote repo. Keep in mind, however, that this pruning does not apply to tags. You'll want to use
--prune-tags for that.