How to delete branches in Git

While working with Git, you likely happen across a situation where you want to delete a git branch. But before jumping into the complexities of deleting a branch, let's see how you would go about deleting a branch in the local Git repository and then in a remote.

To delete a branch, we have first to delete the branch locally and then move forward with deleting the remote branch.

To demonstrate this, I have created a Github repo with a branch to be deleted.

Remote Repository

From the screenshot above I want to delete the branch named test-branch.

Deleting a local branch

First, we list out all the branches (local as well as remote), using the git branch command with -a (all) flag.

$ git branch -a

Output:

login
  master
  *test-branch
  remotes/origin/master
  remotes/origin/test-branch

Note: Make sure you are not in the branch which you want to delete.

In the output above * denotes the current branch I'm in. We can see that I'm currently in test-branch.

So it means that I need to checkout to another branch, in order to checkout to another branch run the command below.

$ git checkout master

Now I've checkout out to master. To confirm run the git branch -a command again.

Output:

login
  *master
  test-branch
  remotes/origin/master
  remotes/origin/test-branch

To delete the local branch, just run the git branch command with the -d (delete) flag, followed by the name (test-branch branch in this case) of the branch you want to delete.

$ git branch -d test-branch

Output:

Deleted branch test-branch (was a4f0911).

Note: You can also use the -D flag which is synonymous with --delete --force instead of -d. This will delete the branch regardless of its merge status.

Even after deleting the branch locally, we can still see the branch in the repository.

Remote Repository

Deleting a remote branch

To delete a remote branch, you cannot use the git branch command. Instead, use the git push command with --delete flag, followed by the name of the branch you want to delete (test-branch branch in this case).

$ git push origin --delete test-branch

Output:

To https://github.com/Pratap22/git-guide.git
 - [deleted]         test-branch

Screenshot of remote repo.

Remote Repository

Finally, the branch was deleted from the repository as well.

Conclusion

I hope this article has helped you with the process of deleting a git branch both locally and remote repository.

If you liked the article, feel free to share it to help others find it!

You may also follow me on LinkedIn and Twitter.

💌 If you’d like to receive more tutorials in your inbox, you can sign up for the newsletter here.

Discussions

Up next