How To Delete A Local And/Or Remote Git Branch

Using git branch and git push --delete to delete Git branches

TL;DR

Use git branch -d BRANCH_NAME && git push REMOTE_NAME --delete BRANCH_NAME to delete both local and remote branch

Written by @bazamel_

Image cover

There are two ways to delete a branch in Git: locally and remotely.

Deleting a Local Branch

To delete a local branch, you can use the git branch command with the -d option, followed by the name of the branch you want to delete. For example:

git branch -d BRANCH_NAME

This command will delete the branch, but only if it has been fully merged into the current branch. If the branch is not fully merged, you can use the -D option instead of -d to force the deletion:

git branch -D BRANCH_NAME

Deleting a Remote Branch

To delete a remote branch, you can use the git push command followed by the —delete option and the name of the remote repository, followed by the name of the branch you want to delete. For example:

git push REMOTE_NAME --delete BRANCH_NAME

This will delete the branch from the remote repository, but it will not delete it from your local repository. If you want to delete the local copy of the branch as well, you will need to use the git branch -d command.

It’s important to note that deleting a branch means you permanently lose all the commits and changes on that branch, so it’s a good practice to make sure that you have a backup of the code or merge it to another branch before deleting it.

Additionally, it is a good practice to check the branch you are deleting is not a protected branch, as it can be a branch that is necessary for the functionality of the project and deleting it may cause problems.