How to delete a git branch from the local and remote repo?

In this post I present a solution on how to delete a git branch from the local and remote repository.

Delete a git branch from the local repository

The following command deletes the given branch from the local repository

git branch -d <branch_name>
  • <branch_name> shall be replaced with your branch name,
  • -D option is a shortcut for --delete --force. The -f or --force in combination with -d (or --delete), allows deleting the branch irrespective of its merged status. [source: man git-branch]

If you are on the branch which you would like to delete, then you will get the following error message

error: Cannot delete branch 'test' checked out at <git_folder_path>

In this case you must switch to another branch, such as master or main:

git checkout main

after that, you can delete the desired branch.

Delete a git branch from the remote repository

In order to delete the branch from the remote repository type the following git command to the command line:

git push -d origin <branch_name>
  • -d (or --delete) deletes all listed refs from the remote repository. [source: man git-branch]

Demonstration

The video below demonstrates the described commands above:

Leave a Reply