How to delete local branch and remote branch in GIT

How to delete local branch and remote branch in GIT
Posted by Gulab Bisht

Dealing with git branches is something which every developer would have come across unless you are living in a cave. While you are creating new branches every day, but it is a rare instance when you need to delete that branch on local and remote as well.

There could be many reasons that you need to delete a branch. Either you are deleting them because you need to clean up the git repository or you need different changes in a remote branch and for that, you need to delete it first.

Here is the complete process on how to delete a branch from local and push it to the desired remote.

Deleting Git Branch from Local

Git branch on local can be deleted with a single command.

git branch -d mybranch

-d flag in the command represents --delete and will delete the branch if you don't have any unmerged commits in it. But if you have unmerged commits in the branch you are trying to delete then it will throw an error.

$ git branch -d mybranch
error: The branch 'mybranch' is not fully merged.
If you are sure you want to delete it, run 'git branch -D mybranch'.

As mentioned in the output of command we ran, you need to use -D to delete the branch which is not fully merged. -D is the combination of -delete and -force to forcefully delete the branch. But be careful with this as you might lose data.

git branch -D mybranch

Deleting Git Branch from Remote

To delete a branch from remote you need to use "git push" command with --delete flag which will delete it from the mentioned remote.

git push origin --delete mybranch

 

One of the biggest things to remember while deleting a git branch from local and remote is that both are maintained differently. Deleting the local branch will not have any effect on the remote branch or vice versa. Both of them need to be deleted separately as represented above.

Tags