To delete branch locally and remotely, you have to use some git commands to remove a target branch on the online repository or from the local repository by following the steps one by one .

To delete a branch from your repository using git, you have to use the below command.

git branch -d [BRANCH-NAME]

Anyway, the following image shows you a remote repository that contains 3 branches. I cloned already all branches except one which under the name “development”.

GitHub Branches

So I will delete “new-file” branch from the local repository. But before that I will show you a figure to understand all branches with its commit refs.

git delete branch

Let’s see how to delete the “new-file” branch from the local repository.

Delete a Branch Locally from the Repository

Actually, git system will not allow you delete the current repository. So you have to make sure that you already on another cursor (branch). Otherwise it will show you the following error.

Error in branch deletion

So you have to move the cursor to another branch using the select command: git switch [branch-name]. Then you can delete it directly by the below command.

git branch -d new-file

Or you can delete it permanently by using the -D flag instead of -d. So it would be written like the below command.

git branch -D new-file

But, if you look at the above figure you will see 2 refs committed there, which are e7f1da9 and 1e2439a, and the question is: does the deletion have any effect on that? Let’s see the answer in the following part.

Effecting of the Branch Deletion on its Logs

Actually, that doesn’t effect on the commits and structure, it only removes the label name of the branch. But if those commits already not merged into the track it will delete all commits and refs to free the spaces.

I deleted the “new-file” branch but the two refs are still there and that to allow me to recreate the same branch name.

Check the following image.

git reflog

Note: the branch deletion only effects on the local repository, but what about the remote repository? Let’s move to the next part to see how to upload this change.

Delete a Branch from the Remote Repository

You will not be able to upload the current remove change to the remote repository, you have to delete the branch directly from the remote repository by the below command.

git push origin :[BRANCH-NAME]

Or you can use another command

git push origin --delete [BRANCH-NAME]
git delete remote branch

Wrapping Up

In this article, you understood how to use git to delete a branch from as a locally and remotely. Also you learned how does it work with examples.