As such, this post will show you how to delete a local and remote Git branch. Before we get to that, let’s run through how Git works on a broad basis.
A Quick Primer on Git
Before we get into the bulk of the article, let’s first give you a quick overview of Git. This is a way to record the activity within a development project. It’s much like the revision functionality found in Google Docs and other software. The hierarchy of a Git “repository” can be summed up in a few points:
There’s a main “track” for the definitive version of your project. This has been called master by tradition, although the naming convention is starting to change to main or trunk.Each repo can have multiple “branches.” These are copies of the trunk and let developers work on sandboxed versions of the project at the same time.You “push” and “commit” changes to the project to your branch.This branch is then merged with trunk to result in a new definitive trunk.
On the whole, Git is great when you want to stick to these principles. Even so, when you want to delete a branch, it can be headache-inducing.
How to Delete a Local and Remote Git Branch
The first step to delete a local and remote Git branch is to understand the makeup of the command you’ll use: Once you grasp this structure, you can adapt it to your needs. To start, let’s look at a local branch. This assumes you are using the command line and have a Git repo to work with. To delete a local branch, you’ll use the git branch command, the -d modifier, and the branch name. In our example, we are using oldbranch, but yours will be specific to your project. Putting it together, we get the following: This tells Git to delete the named branch from your local repo. Despite this, Git may not let you delete a branch. This is because it will contain commits that haven’t yet been merged with other local branches. It could also be because you haven’t “pushed” the branch to a remote repo. To counteract this, use -D as a modifier rather than -d. For remote branches, you’ll use the git push command. Going back to our skeleton, you’ll also need a remote name. This is often origin by convention, although check with your team leader if you’re unsure. To put it all together, you’ll get the following: Depending on the version of Git you’re using, you may have to change the order of the full command: Again, capitalizing the modifier will delete the branch regardless, whereas you’ll often get a confirmation request for lowercase modifiers.
Wrapping Up
On the whole, Git is a powerful language, tool, and development aid. Even so, it’s great when you’re adding things to a Git repo but not so great when removing things. Deleting a local and remote Git branch is a case of learning the command structure. Once you have that down, you’re good to go. If you are exploring using Git for your project, learn how to get started with Git and Github.