Skip to main content

Command Palette

Search for a command to run...

Everything you need to know about deleting branches in Git.

Published
5 min read
Everything you need to know about deleting branches in Git.
O

Software Engineer with a knack for solving complex problems and building efficient, scalable solutions. Experienced in Javascript (VueJs). Currently learning C# so I will be documenting my journey here. I love turning ideas into reality through clean and maintainable code. Always learning, always coding.

Managing branches in Git is an essential part of keeping your project organized, but it can quickly become overwhelming. Imagine running git branch only to find dozens, or even hundreds, of branches cluttering your workspace. Sifting through this list just to find the one you need is frustrating and time-consuming. Worse yet, deleting branches one by one with git branch -D <branch-name> can feel like an endless chore, especially if you're dealing with a large number of branches.

In this guide, we'll cover everything from basic deletion commands to advanced scripting techniques, safety tips, and automation strategies to help you keep your Git branches under control. By the end, you'll have all the tools you need to streamline your Git workflow and keep your repository in top shape.

Different Ways to Delete Git Branches

  1. Understanding the difference between git branch -d and git branch -D

    • git branch -d <branch-name>: Deletes a local branch but only if it has been fully merged.

    • git branch -D <branch-name>: Forces deletion of a local branch, even if it hasn’t been merged. It is the same thing as git branch —delete —force`. Use this with caution.

  2. Deleting a single branch:

    To delete a branch, run:

     #for local branch
     git branch -d <branch-name>
     #for remote branch
     git push origin --delete <branch-name>
    

    For example, to delete the branch add-login-form:

     #for local branch
     git branch -d add-login-form
     #for remote  branch
     git push origin --delete add-login-form
    

    Always verify the deletion with:

     #for local branches
     git branch
     #for remote branches
     git branch -a
    

    Tip: Make sure the branch you're deleting is not currently checked out.

  3. Deleting all branches except main: If you want to delete all branches except for the main branch (often named main or master), use:

     git branch | grep -v "main" | xargs git branch -D
    

    This command deletes every branch except the one you specify. Be sure you're checked out on main or the specified branch before running it.

  4. Deleting Multiple branches using a Bash Script:

    You can use bash commands and scripting for more complex deletions, such as deleting branches by pattern:

    • Delete Local Branches Starting with a Prefix:

        git branch | grep '^  feature/' | xargs git branch -d
      

      This deletes all branches whose names start with feature/.

    • Delete Remote Branches by Pattern:

        git branch -r | grep 'origin/feature/' | sed 's/origin\///' | xargs -I {} git push origin --delete {}
      

      This command removes remote branches that match a specific pattern.

Identifying Patterns in Branch Names

Identifying branch patterns can save you time and avoid mistakes. Use the following steps:

  • List All Branches:

      #for local branches
      git branch
      #for remote branches
      git branch -r
    
  • Filter Branches Using grep:

    • Branches Starting with a Prefix:

        git branch | grep '^  feature/'
      
    • Branches Containing a Substring:

        git branch | grep 'bugfix'
      
    • Branches Ending with a Specific Suffix:

        git branch | grep 'test$'
      
  • Advanced Pattern Matching with Regular Expressions:

    Use grep -E for more complex patterns:

    • Branches with Digits:

        git branch | grep -E '[0-9]'
      
    • Branches with Specific Keywords:

        git branch | grep -E '^  feature.*(refactor|update)'
      

      This shows a list of branches that start with feature and contain either refactor or update.

Examples of Using Patterns to Delete Branches

Once you've identified the branches you want to delete using patterns, combine them with deletion commands:

  • Delete Local Branches Matching feature/:

      git branch | grep '^  feature/' | xargs git branch -d
    
  • Delete Remote Branches Containing bugfix:

      git branch -r | grep 'bugfix' | sed 's/origin\///' | xargs -I {} git push origin --delete {}
    

When and Why to Delete Git Branches

Regularly deleting old or unused branches is essential for several reasons:

  • Keep the Repository Clean: Reduces clutter and makes it easier to navigate.

  • Avoid Confusion: Helps team members avoid working on outdated or irrelevant branches.

  • Improve Performance: Especially in large repositories, fewer branches can lead to better performance during Git operations.

Safety Tips Before Deleting Branches

Before you delete branches, follow these tips to ensure you don't lose important work:

  • Check Out a Safe Branch: Make sure you're on a branch like main or develop before deleting other branches.

  • Verify Merges: Use git log or git diff to ensure the branch has been fully merged before deletion.

  • Recovering Deleted Branches: In case of accidental deletion, git reflog can help recover recently deleted branches.

Handling Protected Branches

Some branches may be protected by your repository settings, especially in collaborative environments:

  • Protected Branches: Typically, branches like main or master are protected to prevent accidental deletion or direct pushes.

  • Modifying Protection Settings: If you need to delete a protected branch, you may require admin rights or have to modify branch protection settings in your repository hosting service (e.g., GitHub, GitLab).

Common Errors When Deleting Branches and How to Resolve Them

  • error: Cannot delete branch '...' checked out at '...': This happens when you're trying to delete a branch that is currently checked out. Switch to another branch first.

  • Permission Errors: When deleting remote branches, you might encounter permission issues. Ensure you have the necessary rights, or contact the repository admin.

Automating Branch Deletion with CI/CD Tools

For a more automated approach, integrate branch cleanup into your CI/CD pipeline:

  • GitHub Actions: Set up a workflow to delete branches that have been merged.

  • GitLab CI: Use scheduled pipelines to automatically remove old branches.

Example for GitHub Actions:

name: Cleanup Merged Branches

on:
  schedule:
    - cron: '0 0 * * 0' # Runs weekly

jobs:
  cleanup:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Delete merged branches
        run: |
          git fetch --prune
          git branch --merged | grep -v 'main' | xargs -n 1 git branch -d

Alternative Tools or Plugins for Managing Git Branches

Consider using tools like git-extras or git-branch-cleaner for enhanced branch management. These tools offer additional features such as interactive deletions and more advanced filtering options.

Final Checklist

  • Review and double-check branch names before deleting.

  • Ensure all important changes are merged or saved.

  • Regularly clean up branches to keep your workflow efficient and organized.

With these tips, you'll be able to manage your Git branches more effectively and keep your repository in top shape!