How to delete a Git branch locally

Whether you use GitFlow, GitHub Flow or any other branch driven development strategy, you will inevitably end up with a local Git repository filled with branches you no longer need. Which is why it’s good to know the command to delete Git branches locally and permanently so they don’t pollute your local development environment.

How to delete local Git branches

To issue the command to delete a local Git branch, follow these steps:

  1. Open a Git BASH window or Command Window in the root of your Git repository
  2. If necessary, use the git switch or checkout command to move off the branch you wish to delete
  3. Issue the
    git branch --delete <branchname>

    command to delete the local branch

  4. Run the git branch -a command to verify the local Git branch is deleted

Git Error: Cannot delete branch

One rule of local Git branch deletion is that you cannot delete a branch that is currently checked out. Otherwise, you run into the ‘cannot delete branch’ error as you can see in the example below:

[email protected] /c/local/branch (main)
$ git branch -a
* main
new-branch
old-branch
[email protected] /c/local/branch (main)
$ git branch --delete main
error: Cannot delete branch 'main' checked out at 'C:/git/delete'

In the above example, the user tried to delete the main Git branch while the it was checked out, which caused an error. However, deletion of the local Git branches named new-branch 0r old-branch would run without error:

[email protected] /c/local/branch (main)
$ git branch --delete old-branch
Deleted branch old-branch (was 44a55a1).

Delete local Git branch command

The command to delete a local git branch can take one of two forms:

  • git branch –delete old-branch
  • git branch -d old-branch

The only difference is the fact that the second local branch delete Git command uses an abbreviated syntax. Both commands do the exact same thing.

Remove vs local Git branch deletes

It should be noted that when you delete a local Git branch, the corresponding remote branch in a repository like GitHub or GitLab remains alive and active. Further steps must be taken to delete remote branches.

git no upstream branch error fix

When you delete a local Git branch, the deletion will not be reflected in remote repos like GitHub or GitLab.

 

 

 

 

App Architecture
Software Quality
Cloud Computing
Security
SearchAWS
Close