Essential Git Skills: How to Delete Remote Branches

By Mihir Pipermitwala · · 8 min read

⚡ TL;DR

Keep your repository clean and organized. This guide walks you through how to delete both local and remote branches in Git, step by step.

Managing branches in Git is a crucial skill for keeping your repositories clean and organized. Whether you’re wrapping up a feature or cleaning up outdated code, knowing how to delete both local and remote branches is essential. In this guide, we’ll walk you through the process of deleting branches and explore some advanced tips and best practices.

To delete a remote branch in Git, run git push origin --delete branch_name; to delete a local branch, run git branch -d branch_name (or -D to force it). Then run git fetch -p to prune stale remote-tracking references, and enable your hosting platform’s “auto-delete branches” setting so merged pull request branches disappear automatically.

Deleting Local Branches

Before diving into remote branches, it’s important to understand how to delete branches locally. Deleting local branches is often done to clean up branches that are no longer needed, such as after merging a feature branch into the main branch.

How to Delete a Local Branch

To delete a local branch, use the following command:

Copy
git branch -d branch_name

Replace branch_name with the name of the branch you want to delete. This command will only delete the branch if it has already been merged. If the branch has not been merged, you’ll need to use the -D flag to force delete it:

Copy
git branch -D branch_name

Why Delete Local Branches?

Deleting local branches keeps your repository free of clutter, ensuring you’re not working with outdated or unnecessary code. Regular cleanup of local branches prevents confusion and helps maintain a tidy workspace.

Deleting Multiple Local Branches at Once

If you have several local branches to delete, you can use a command to delete them all at once:

Copy
git branch | grep 'pattern' | xargs git branch -d

This command deletes all local branches matching a specific pattern. Replace pattern with the name or part of the branch name you want to delete.

Deleting Remote Branches

Once you’ve cleaned up your local branches, you may also need to delete remote branches. Remote branches should be deleted when they are no longer needed or have been merged and closed.

How to Delete a Remote Branch

To delete a remote branch, you’ll use the following command:

Copy
git push origin --delete branch_name

In this command, origin refers to the remote repository, and branch_name is the name of the branch you wish to delete.

Verifying the Deletion

After deleting a remote branch, you can verify the deletion by fetching the latest updates from the remote repository:

Copy
git fetch -p

The -p flag, short for --prune, cleans up any references to the deleted branch in your local repository.

Deleting Remote Branches in a Multi-Remote Setup

If your project has multiple remotes, such as origin and upstream, you can delete a branch from a specific remote using:

Copy
git push upstream --delete branch_name

This command deletes the branch from the upstream remote while leaving it intact on origin.

Handling Errors When Deleting Branches

Sometimes, you may encounter errors when trying to delete a branch, such as:

  • Branch is protected: Ensure you have the necessary permissions or adjust the protection settings.
  • Branch not fully merged: If a branch is not fully merged, you may need to force delete it using the -D flag for local branches or ensure the branch is no longer needed.

Advanced Tips for Branch Management

Automating Branch Cleanup with Git Hooks

You can automate branch cleanup by using Git hooks. For example, a post-merge hook can automatically delete local branches that have already been merged into your current branch:

Copy
#!/bin/bash
# .git/hooks/post-merge — delete local branches that are fully merged
# into the current branch (typically main after a git pull).

git branch --merged HEAD | grep -vE '^\*|main|master|develop|release' | \
  xargs -n 1 git branch -d

Save this as .git/hooks/post-merge, make it executable with chmod +x .git/hooks/post-merge, and it will run after every git merge or git pull. The important detail: git branch --merged HEAD lists the branches that were actually merged into the current branch — not the current branch itself (which is excluded by grep -v '^\*'). git branch -d is the safe flag, so a branch that isn’t fully merged is never deleted. One caveat: Git only runs hooks from .git/hooks, so this automation stays local — it won’t propagate to teammates through the repository. For a shared solution, use the auto-delete settings on your hosting platform (see below).

Deleting Stale Remote Tracking Branches

Even after deleting a remote branch, your local repository might still have references to it. Clean these up with:

Copy
git fetch -p

The --prune option removes stale remote-tracking branches that no longer exist on the remote.

Recovering a Deleted Branch

If you accidentally delete a branch, you can recover it using the commit hash from the reflog:

Copy
git reflog

Identify the commit hash and restore the branch with:

Copy
git checkout -b branch_name commit_hash

Auto-Deleting Merged Branches on GitHub and GitLab

Instead of (or in addition to) local hooks, let your hosting platform delete the remote branch for you the moment a pull request is merged:

  • GitHub: In the repository, go to Settings → General → Pull Requests and check “Automatically delete head branches.”
  • GitLab: In the project, go to Settings → Merge requests, and enable “Auto-delete source branch on merge” (or tick the box per merge request when creating it).
  • Bitbucket: When merging a pull request, enable “Delete branch on merge” in the merge dialog, or check Repository settings → Branch settings for defaults.

With this enabled, every merged PR’s source branch is removed from the remote automatically, and a local git fetch -p keeps your remote-tracking refs in sync.

Visualizing Branches with Git GUI Tools

For those who prefer visual tools, Git GUI applications like GitKraken, Sourcetree, or Git Extensions provide a graphical interface for managing and deleting branches. These tools can make it easier to handle complex branching scenarios.

Using Git Aliases for Branch Management

To streamline your workflow, you can create Git aliases for common commands. For example:

Copy
git config --global alias.delete-branch 'push origin --delete'

This alias allows you to delete remote branches with a simple git delete-branch branch_name command, saving time and reducing errors.

Best Practices for Branch Management

  • Use Descriptive Names: Choose clear and descriptive names for your branches to make their purpose easily identifiable.
  • Keep Branches Short-Lived: Merge changes as soon as they are ready to avoid long-lived branches that can cause merge conflicts.
  • Regularly Clean Up: Periodically delete branches that are no longer needed, both locally and remotely.
  • Enforce Branch Protection: Protect critical branches like main or master to prevent accidental deletions or force pushes.
  • Automate Deletion: Enable auto-delete on merged pull requests and use a post-merge hook so cleanup happens without manual effort.

Conclusion

Mastering branch management in Git, including deleting both local and remote branches, is an essential skill for any developer. By following the steps and best practices outlined in this guide, you can keep your repositories clean, organized, and free of unnecessary clutter. Whether you’re working solo or in a team, these techniques will help you maintain a streamlined workflow and prevent potential issues down the line.

References

FAQ

How do I delete a remote branch in Git?

Run git push origin —delete followed by the branch name; this removes the branch from the remote repository named origin. Then run git fetch -p to prune the stale remote-tracking reference from your local repository. If your project has multiple remotes, substitute the remote name, such as git push upstream —delete for the upstream remote.

How do I delete a local branch in Git?

Run git branch -d with the branch name, which safely deletes the branch only if its commits have already been merged. If the branch is not fully merged and you are certain the work is unwanted, force deletion with git branch -D. Afterwards, git fetch -p cleans up any stale remote-tracking references left behind.

How do I automatically delete branches after merging a pull request?

Enable your hosting platform’s auto-delete setting: GitHub offers “Automatically delete head branches” under repository Settings, GitLab offers “Auto-delete source branch on merge” in merge request settings, and Bitbucket offers “Delete branch on merge” in the merge dialog. Locally, a post-merge Git hook can also delete branches already merged into your current branch automatically.

Can I recover a deleted Git branch?

Yes. Run git reflog to list recent HEAD movements and find the commit hash the deleted branch pointed to, then recreate the branch with git checkout -b branch_name commit-hash. The reflog retains this history locally for a default period of 90 days, so recovery works even after both local and remote deletion, as long as the local repository still exists.

Mihir Pipermitwala

Written by Mihir Pipermitwala

Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.

More about Mihir →
Scroll down to load comments...
Related Blogs
Go JSON v2: A Practical Migration Guide to encoding/json/v2

Go JSON v2: A Practical Migration Guide to encoding/json/v2

Migrate a Go REST API to encoding/json/v2 in 7 steps: struct tags, omitempty, unknown fields, error handling, and jsontext streaming, plus a v1 vs v2 comparison.

GOTUTORIALDEVELOPER TOOLS

November 12, 2026

Fix Git Checkout 'Filename Too Long' Error on Windows

Fix Git Checkout 'Filename Too Long' Error on Windows

Learn how to solve the 'Filename too long' or 'unable to create file' error in Git on Windows. Enable core.longpaths globally or config Git during clone.

BITBUCKETGITGITHUBGITLAB

April 01, 2024

Understanding Git Merging: Orthogonal vs Recursive Perspectives

Understanding Git Merging: Orthogonal vs Recursive Perspectives

Understand Git's ort and recursive merge strategies. What orthogonal history means, why ort replaced recursive as the default in Git 2.34, and how conflicts are resolved.

BITBUCKETGITGIT MERGINGGITHUBGITLAB

March 26, 2024

Related Tutorials
Essential Git Skills: How to Delete Remote Branches

Essential Git Skills: How to Delete Remote Branches

Keep your repository clean and organized. This guide walks you through how to delete both local and remote branches in Git, step by step.

BITBUCKETDELETE LOCAL BRANCHDELETE REMOTE BRANCHGITGIT BRANCH CLEANUP AUTOMATION

June 12, 2024

Show an Offline Message for No Internet in Flutter

Show an Offline Message for No Internet in Flutter

You have to use the 'Connectivity Flutter Package' to achieve this feature on your App. This package helps to know whether your device is online or offline.

CONNECTIVITY PLUSDEPENDENCIESFLUTTERFLUTTER DEVELOPMENTFLUTTER PACKAGES

April 09, 2024

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Implement TabBar and TabBarView in Flutter step by step — customize tab indicators, enable scrollable tabs, and change tabs programmatically.

CODINGDEFAULT TAB CONTROLLERFLUTTERLEARN TO CODETAB CONTROLLER

July 26, 2023

File Manipulation in Flutter: Best Practices & Examples

File Manipulation in Flutter: Best Practices & Examples

Master Flutter file manipulation — permission management, directory handling, and practical read-write scenarios to elevate your app's file handling.

CODINGFLUTTERFLUTTER DEVELOPMENTFLUTTER FILE OPERATIONFLUTTER PATH PROVIDER

June 30, 2023

Related Recommended Services
Visual Studio Code for the Web

Visual Studio Code for the Web

Build with Visual Studio Code, anywhere, anytime, in your browser.

IDEVISUAL STUDIOVISUAL STUDIO CODEWEB
Renovate | Automated Dependency Updates

Renovate | Automated Dependency Updates

Renovate Bot keeps source code dependencies up-to-date using automated Pull Requests.

AUTOMATED DEPENDENCY UPDATESBUNDLERCOMPOSERGITHUBGO MODULES
Best XML Formatter and XML Beautifier

Best XML Formatter and XML Beautifier

Online XML Formatter will format xml data, helps to validate, and works as XML Converter. Save and Share XML.

XMLXML BEAUTIFIERXML CONVERTERXML FORMATXML FORMATTER
Kubecost | Kubernetes cost monitoring and management

Kubecost | Kubernetes cost monitoring and management

Kubecost started in early 2019 as an open-source tool to give developers visibility into Kubernetes spend. We maintain a deep commitment to building and supporting dedicated solutions for the open source community.

CLOUDKUBECOSTKUBERNETESOPEN SOURCESELF HOSTED
Related Recommended Stories
How GitHub reduced testing time for iOS apps with new runner features

How GitHub reduced testing time for iOS apps with new runner features

Learn how GitHub used macOS and Apple Silicon runners for GitHub Actions to build, test, and deploy our iOS app faster.

IOSGITHUBTESTINGRUNNER
5 ways to transform your workflow using GitHub Copilot and MCP

5 ways to transform your workflow using GitHub Copilot and MCP

Learn how to streamline your development workflow with five different MCP use cases.

AGENT MODECODING AGENTCOPILOTFIGMAGITHUB
One weird trick for powerful Git aliases

One weird trick for powerful Git aliases

Advanced Git Aliases

ALIASALIAS TEMPLATEATLASSIANBITBUCKETGIT
Awesome Python

Awesome Python

An opinionated list of awesome Python frameworks, libraries, software and resources

AWESOMEAWESOME PYTHONCOLLECTIONSGITHUBPYTHON
Related Recommended Tools
Find out what websites are built with - Wappalyzer

Find out what websites are built with - Wappalyzer

Find out the technology stack of any website. Create lists of websites and contacts by the technologies they use.

ADD ONSANALYTICSAPP STOREAPPLEBOOKING
Sourcetree | Free Git GUI for Mac and Windows

Sourcetree | Free Git GUI for Mac and Windows

A Git GUI that offers a visual representation of your repositories. Sourcetree is a free Git client for Windows and Mac.

GITGITHUBGITLABATLASSIANBITBUCKET
Related Recommended Videos