How to delete local and remote Git branch

Photo by Yancy Min on Unsplash

How to delete local and remote Git branch

Git Dec 6, 2022

The first step to deleting local and remote Git branches is to understand the composition of the command you will be using:

gitcommand>modifier>remote_name>branch_name>

Once you get the hang of this structure, you can tailor it to your needs. Let's start with the local branch. This assumes you are using the command line and have a Git repository to work with.

To delete a local branch, you use the command git branch, modifier, -dand branch name. In our example, we use oldbranch, but yours will be specific to your project. Putting it all together, we get the following:

git branch - d oldbranch

This tells Git to remove the specified branch from your local repo. Regardless, Git may not let you delete the branch. This is because it will contain commits that have not yet been merged into other local branches. It could also be because you didn't "push" the branch to the remote repo.

To counteract this, use as a modifier -Drather than -d.

For remote branches, use the git push. Back to our skeleton, you will also need a remote name. This is usually origin, but if you're not sure, check with your team leader. Putting it all together, you get the following:

git push - d origin remote branch

Depending on the version of Git you're using, you may need to change the order of the full command:

git push origin - delete remote branch

Again, if you use a capitalized modifier, the branch will be deleted regardless, whereas you will often get a confirmation prompt for lowercase modifiers.

Conclusion

All in all, Git is a powerful language, tool, and development tool. However, it's great when you add something to a Git repository, but not so great when you remove something. Deleting local and remote Git branches is a case of learning about the command structure. Once you have that, you can start.

Tags

Anurag Deep

Logical by Mind, Creative by Heart