My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
How To Delete a Git Branch Locally and Remotely

How To Delete a Git Branch Locally and Remotely

Learn the git commands and workflow required to delete branches both locally and remotely

Catalin Pit
·Apr 16, 2021·

2 min read

In this article, you will learn how to delete a branch from your project, both locally and remotely.

It's important to note that you need to delete the branch both locally and remotely manually. Deleting one will not delete the other. Thus, if you want to get rid of a branch, you need to delete it from both places.

Delete a Git branch locally

Before going further, it's important to note that there are two types of local branches. Each type requires a specific flag to delete it.

Also, you need to be aware that you cannot delete a branch you are using. Thus, before deleting a specific branch, you must change to another branch (e.g. main).

Scenario 1

The first scenario is when you want to delete a branch that is already pushed and merged with remote branches.

You can do so with the following command:

git branch -d your/branch

In the above command, the flag `-d' is the shorthand for the word delete.

Scenario 2

The following scenario is when you want to delete a branch irrespective of its status. Or a branch that is not already pushed and merged with remote branches.

In simpler words, it deletes a branch irrespective of its merge status. You can delete such a branch with the following command:

git branch -D your/branch

Be aware that the above command deletes your branch even if it contains changes that are not pushed yet. The reason is that the -D flag is the shorthand for --delete --force. Use this command carefully!

Note: It's better to use the first scenario command whenever possible. That's because the `-d' flag checks the merge status, and it warns you if the changes are not merged. The second scenario command does not check the merge status, and it deletes the branch automatically.

Delete a Git branch remotely

Additionally, you can delete a remote Git branch. In this case, you use the command git push rather than git branch.

git push origin --delete your/branch

Using the above command only deletes your branch remotely. If you want to delete a branch locally, you must manually use one of the above commands.


Alternatively, you can delete all local Git branches in one go.

Conclusion

In this article, you learnt how to delete a branch both locally and remotely. Make sure you understand the caveats of each command.

Additionally, you might be interested in Git Aliases. The aliases will improve your experience significantly, and it is going to save you time as well.