Delete Git Branch from Local and Remote (With Examples)

Delete Git Branch from Local and Remote (With Examples)

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. Ease cleanly 

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 remote.

Deleting Git Branch from Local

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

git branch -d my-branch

-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 and you are trying to delete then it will throw an error.

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

As mentioned in the output of the command we ran, you need to use the "-D" option to delete the branch which is not fully merged. "-D" option 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 my-branch

Deleting Git Branch from Remote

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

git push origin --delete my-branch

Conclusion

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