304 North Cardinal St.
Dorchester Center, MA 02124
Wondering how to Git delete a local branch or a remote one only as you have merged the branch already? Here’s a quick guide for doing cleanup locally also.
Today if you are a CS grad, it is very hard to difficult syntax for each and every language or even something as basic as Git. Unfortunately, some Git commands do not have a syntax which can be remembered also.
The explained use case raised the need to have this guide. I have been using Git for long long time now but still, there are times I need to look syntax for various things.
This is why I am writing this guide on how to delete the git branch.
Below are couple of sections that will help you with git commands along with examples.
When you want to delete just the local branch without affecting the remote branch or removing it, below listed few commands might help.
$ git branch -d <local_branch>
Let’s understand each part of the command :
-d : A flag that tells git to delete the branch. Alternatively, we can use
--deletealso. However, to force delete the branch in case of conflicts we can use
-D which is an alias for
$ git branch -D <local_branch>
[su_note note_color=”#FFF9C4″]But for this to work you need to check out different branches before deleting one specific branch. In simple terms, one cannot delete a branch he is working on. Even force delete won’t work.
In such a case, commands that you would need to follow will be :
$ git checkout master $ git branch -D <local_branch>
Another thing to take care of while using
-D is that it will delete any unmerged branch also. So to be on safer side we should always use
[su_label type=”success”]Suggested read[/su_label] How to git remove file from commit after push or staging
When you want to work with a remote branch and delete a remote git branch, you probably need this guide.
This might be a bit complex as opposed to git delete local branch. This is because of the fact the syntax varies depending on the git versions.
Well, I will be listing commands for all git versions. However, you need to first verify the git version you are using. Check it with the command :
$ git --version
Use this command if you have a git version v1.7.
$ git push <remote_repo> --delete <remote_branch>
$ git push <remote_repo> -d<remote_branch>
$ git push <remote_repo> :<remote_branch>
These commands will push changes to remove a branch from remote git repository so we need to be very careful of what we are doing.
[su_label type=”success”]Suggested read[/su_label] How to clone a branch in git with just 2 commands
Once changes are pushed, other developers taking a pull of the repo will lose the branch and won’t see it.
If somebody is already working on that branch, they might need to run below command to see the changes.
$ git fetch --all --prune
Here’s a more definite guide by Scott Chacon on dealing with branches.