Git​‍​‌‍​‍‌​‍​‌‍​‍‌ Remove Local Branch: Safe & Simple Guide

We’ve all had that. You open your terminal, type git branch to know which branch you’re on, and instead of a short list, you get a list of 20, 30, or even 50 old branches. There will be a feature-login-page branch, a fix-typo-header branch, an experiment-new-api branch, and a temp-save-work branch on the list. It looks like a cluttered desktop with dozens of old screenshots and random PDF files spread all over the place.

It’s sloppy and distracting and makes finding the branch you really want way harder than it should be.

Git is a modern version control backbone that allows us the freedom to branch out for every small experiment, bug, or feature without ruining the main codebase. This is an extremely powerful feature, but it also has a drawback, which is the accumulation of digital clutter. Creating branches has become routine and simple nowadays but deleting them is still a prime consideration to keep your development environment clean and healthy. Just think about it. A bloated repo not only looks ugly but it can be confusing, discourage developers from making the right commits, and even lead to working on the wrong version of your code in the end.

This article is all about teaching you how to safely git remove local branches. We will highlight the usual Git checks that help make the process safe, how to force the deletion when absolutely necessary, and the best way to make sure you don’t lose valuable work.

What’s a Branch Anyway?

Before we jump into the how-to getting rid of branches, I guess it makes sense to first clarify exactly what we are deleting. When you execute a git branch command, and the terminal prints you a list of local branches, what are these?

Local Branch

A local branch is kind of your own little parallel development line on your local machine. If you were to create a branch for a new feature that you want to implement, this branch can be compared to a pointer that points at a certain commit. When you commit new changes the pointer automatically moves forward.

Don’t confuse a local branch with a remote one.

  • Local branches are just your branches that live in your computer. You control them 100%.
  • Remote branches represent the state of branches on a remote repository (server on GitHub, GitLab, Bitbucket, etc.).

When you git remove local branch, you simply remove the pointer that refers to the commit on your local machine. Deleting the branch won’t be the same as removing the code from the server (unless you run another command that does that), and it won’t be the same as deleting the commit history either, as you can always get it back.

Lame Explanation: Local branch is a pointer to a commit

Why bother? Local branches are, in fact, only pointers. Besides, they take only a small amount of disk space. Why bother deleting them?

Actually, one reason is to ward off “branch rot”. When you have many branches that are not being used, it will be tough for you (or other people) to distinguish between the active and stale branches. You might mistakenly do a checkout on feature-login of three months ago instead of the latest feature-login-v2 and waste a couple of hours working on outdated code.

In a software development team, deleting merged branches regularly can be considered a standard housekeeping practice. Once a feature branch is merged into the main branch (typically main or master), the local branch that held that feature is no longer needed and thus keeping it around only serves as clutter.

What can go wrong with deleting branches?

Deleting can be scary, especially when learning how things work in Git. You might ask yourself, what will happen if I accidentally delete something that I still need? Well, the first thing is to have a look on what the common mistakes can be and how Git helps the users to avoid the happening of these mistakes.

Data Loss

The biggest fear in situations such as this is one of losing data. Say that you have been developing a new feature for a whole week only on a branch other than the main one, and now you want to delete that branch without merging it, then recovering the lost work is going to be probably very hard.

Luckily Git is more intelligent than we tend to think. It comes with some great safety features which prevent you from accidentally deleting the work that you haven’t merged into the current branch. If you attempt to delete a branch that contains some changes not yet in your current one, Git will stop you by displaying an error message. We will discuss how to bypass this warning later on, but just knowing that it exists may already give you some sense of security.

Mixed up with remotes

Another source of confusion can be local/remote branches. A local beginner trying to get rid of the local branch may be fantasizing that they could create massive trouble for the whole team through deleting this branch.

Local deletion is just one aspect of local processing not connected to the remote repository. Suppose, you have done a push and your branch is at GitHub. Then, when deleting it on your laptop, it still remains on GitHub. On the other hand, if one deletes a branch on GitHub, this does not mean that it is automatically deleted on one’s laptop. One has to do the cleaning afterwards.

Keep Safe And Only Delete Branches You Know

One good habit is to verify the current status of your working area before you execute commands which will delete stuff or make any changes.

If you run git status, it will show you if there are some changes that you have not yet committed. In that case, you can either commit or stash the changes. Before changing or deleting the branches, it also makes sense to have “zero” uncommitted changes.

Removing Local Branches the Conventional Way

The most typical situation for branch removal might be a branch which has been merged already. You create a new branch, develop a feature, after that a pull request is done and the main branch gets updated. Now, you are good to delete your feature branch.

The Safe Delete Command (-d)

The main way of how to git remove local branch command is:

git branch -d <branch_name>

Do pay attention to the lowercase “-d”. This is a shorthand for “delete”, but the actual meaning is something like “delete if it is safe”. In other words, this is the safety mode of Git. By running this command, Git will verify the branch that you want to delete against your current branch (as well as its upstream relationship).

If the branch you are attempting to delete is a branch which has new work on it that you have not merged into your current branch, Git will not permit you to do it. Instead, a failure will be returned thus you are protected against accidental loss of data.

Step By Step Real Example

Imagine a situation in which you would want to remove the branch feature-login as it is done. These are the steps.

Step 1: move to a branch. 

Other than feature-login (git branch -d fails if the branch you want to delete is checked out).

git checkout main

Step 2: update your main branch (optional but recommended)

This is just sort of a red-tape work. Make sure the main branch is up to date before you delete old branches. This way, you know for sure that Git is aware of the fact that the work from the branch to be removed has been merged.

git pull origin main

Step 3: delete the branch

git branch -d feature-login

Step 4: look for the confirmation message

If the branch has already been merged, it will be deleted and a notification will be printed:

Deleted branch feature-login (was a1b2c3d).

The hash (was a1b2c3d) shows exactly where that branch was pointing before it got deleted.

When You Need More Than -d

Sometimes, you want to delete a local branch independently of whether the work has been merged or not. For example, you can have a premature idea that you want to delete your experimental branch right away.

Using the -D flag (force Delete)

Assuming you have already tried deleting the branch with the standard way, and Git refused. It throws out the suggestion with a different command that is force delete:

git branch -D <branch_name>

Note that the uppercase -D is used here and that it is simply a shorthand for the command git branch –delete –force.

Which scenarios would require it?

Is it really necessary to delete a branch that hasn’t been merged?

  • Unfinished Work: You abandoned the branch, for example, you wanted to try out the new library or experiment with a different way of coding, and after a few hours, you realized it wasn’t going to work. Hence, you want to discard the experiment completely. You do not want to pollute main with a bad commit that you don’t want to be merged, so you just want to get rid of that branch.
  • Duplicate Work: Perhaps, you started fixing the same bug as a colleague but that person fixed it in the different branch which got merged first. So, your branch is now redundant.

In these cases, Git will refuse your request by default because it detects unmerged commits. Therefore, you need to tell Git that it is okay to delete the branch anyway.

Warning

Just be careful when doing this. The -D is a destructive operation that will result in the loss of commits if you forcibly delete an unmerged branch. However, the commits will not be permanently lost immediately, as Git reflog would allow you to recover them for a limited time. But, the process of recovery is quite complex and nerve-racking.

Always double-check that the code on a branch is no longer needed before using -D.

Example scenario

Let’s say you created a branch called a test-experiment. You wrote some code, decided it was terrible, and now you want to get rid of it.

You would first try to do so the safe way:

git checkout main

git branch -d test-experiment

The answer from Git will be:

error: The branch ‘test-experiment’ is not fully merged.

If you are sure that you want to delete it, run ‘git branch -D test-experiment’.

Git is trying to protect you. However, since you are aware that you want to get rid of that work, you use the force command as below:

git branch -D test-experiment

Outcome:

Deleted branch test-experiment (was e4f5g6h).

Verify and Cleanup

Following any deletion commands you performed, it is a good habit to verify if branches have been totally removed and that all is neat and tidy.

Check that they are really gone

To confirm that you have successfully managed to remove the local branch, simply repeat the command that lists the branches.

git branch

Or, for a little more detail:

git branch –list

The feature-login or test-experiment branch should no longer be listed. However, if you do see it, try to recall whether you got an error message during the deletion step or not.

Pruning branches that are no longer available

There are situations when your local Git still refers to branches that were deleted on the remote (for example, you deleted them via the GitHub web interface after the merge of the Pull Request).

Do the following if you want to see the listing of all branches (both local and remote) and you notice that the remote branch is one that was already deleted on the server:

git branch -a

And you will see something like remotes/origin/feature-login even if the local feature-login branch has been removed.

Use this pruning command to get rid of those invisible branches:

git remote prune origin

What this command actually does is that it requests from your remote (origin) to list the branches that are currently available, and then it deletes any references locally to branches that have been deleted on the remote. Consequently, your branch list will always be clean and precise.

Fixing Common Mistakes

Even if the issue is as straightforward as running git branch -d, that doesn’t mean things can’t go wrong. When the developers attempt to remove local branches, there are two mistakes that the majority of them will encounter.

Error: “Cannot delete branch ‘x’ checked out at…”

The Error:
error: Cannot delete branch ‘feature-login’ checked out at ‘/Users/dev/project’

The Cause:
Deleting a branch that is currently checked out is failing because you are on the branch you want to delete. This is similar to cutting a branch of a tree on which you are sitting. Instead, switch to a safe branch like main first.

The Fix:
git checkout main

git branch -d feature-login

Error: “The branch ‘x’ is not fully merged”

The Error:
error: The branch ‘feature-login’ is not fully merged.

If you are sure you want to delete it, run ‘git branch -D feature-login’.

The Cause:
Git has realized that the branch you want to delete has commits which are not found in the branch you’re currently on. It foresees that you could have simply forgotten to merge your changes.

The Fix:
You’ve got two options:

  • Merge the work: If those changes were meant to be kept after all, the branch has to be merged first. (git merge feature-login)
  • Force Delete: If you genuinely want to get rid of the changes, then the capital D flag has to be used. (git branch -D feature-login)

Summary: Keep Your Workflow Clean

Professional developers maintain their Git repositories in a clean state. While it may be effortless to let branches pile up, a messy workspace gathers confusion over time. Knowing how to remove local branches without risking your code is a vital skill that will help you stay focused on your development work.

Let’s recap the key commands we covered:

  • git branch -d <branch_name>: The safe way to delete a branch. Use this command for removing branches that have already been merged. It has the side effect of protecting you from accidental data loss.
  • git branch -D <branch_name>: The force way to delete a branch. Use this command for abandoning your experiments or wanting to permanently get rid of unmerged work.
  • git checkout main: The pre-requisite. Before being able to delete a branch, the user needs to switch to the different one.

By becoming familiar with the different meanings of the flags -d and -D, you can clean up your terminal without worrying about getting rid of essential codes. So why not open your terminal and run the git branch command now? If you find a list of features you finished months ago, spend a few minutes deleting them. You will thank yourself for that in the future.

Meta data

Meta titleGit Remove Local Branch: A Safe & Simple Guide

Meta descriptionLearn how to git remove local branch safely without losing code. This guide covers safe delete vs. force delete commands and troubleshooting ​‍​‌‍​‍‌​‍​‌‍​‍‌tips.

Leave a Reply

Your email address will not be published. Required fields are marked *