How to Delete Both Local and Remote Branches in Git

After finishing the work on a branch and merging it into the main master, it is recommended to delete it. Local and remote branches are entirely separate objects in Git. Deleting one would not remove the other, even if there is a tracking connection between them. So, if you need to delete both local and remote branches, delete them separately. Let’s have a look at how to do it!

How to Delete a Local Branch in Git

Git does not allow deleting a branch you are currently on, thus make sure to checkout the branch that you do not want to delete. For checking out from the current branch, run the git checkout command:

git checkout <branchname>

Then, invoke the git branch command with -d or -D option (shortcut for --delete) will delete the <branchname>. If you are sure to delete the branch permanently, you can use the capital -D option. You can delete more than one branch:

git branch -d <branchname>

If the branch has a reflog, it will be deleted either.

The -f or --force flag in combination with -d (or --delete), allows deleting the branch containing unmerged changes.

Use the -f flag very carefully, as it easily may cause data loss.

How to Delete a Remote Branch in Git

To delete a remote branch use the git push command with the "--delete" flag:

git push <remote_name> --delete <branch_name>

In most cases, the remote branch name is the origin. So, your command will most probably look like:

git push origin --delete <branchname>

In git versions older than 1.7.0 the command will be as follows:

git push origin :<branch>

How to Delete Remote-Tracking Branch

To delete remote-tracking branch run command:

git branch --delete --remotes <remote>/<branch>

Shorter version:

git branch -d -r origin/<remote branchname>

To delete multiple obsolete tracking branches run the git fetch command with the --prune option:

git fetch <remote> --prune

Shorter version:

git fetch <remote> -p

The git checkout and git branch Commands

The git checkout command is used for switching branches or restoring working tree files. It operates on files, commits, and branches. The git checkout command allows switching between multiple features in just a single repository. It operates with the git branch command. It updates the files in the working directory to match the version stored in that branch instructing Git to record all the commits.

The git fetch Command Working with Remote Branches

Git stores the local and remote commits and separates through the use of branch references. So as to see the list of the local branch references, you should run the git branch command. To see the remote branches, you should use the -r flag with git branch. You can examine the remote branches with the git checkout and git log commands and after approving the changes of the remote branch, run git merge to merge it into the local branch.

Do you find this helpful?

Related articles