Delete Detached Branches

GitGitBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

When working with Git, it's common to create and switch to detached branches. These branches are not associated with any specific branch and are usually used for testing or experimentation. However, over time, these branches can accumulate and clutter your repository. In this lab, you will learn how to delete all detached branches in your Git repository.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/BranchManagementGroup(["`Branch Management`"]) git/BranchManagementGroup -.-> git/branch("`Handle Branches`") subgraph Lab Skills git/branch -.-> lab-12721{{"`Delete Detached Branches`"}} end

Delete Detached Branches

You have a Git repository with several detached branches that you no longer need. These branches are cluttering your repository and making it difficult to manage. You want to delete all detached branches to clean up your repository.

To complete this lab, you will use the Git repository git-playground from your GitHub account, which comes from a fork of https://github.com/labex-labs/git-playground.git. Do not check "Copy the master branch only".

  1. Clone the repository, navigate to the directory and configure the identity:
git clone https://github.com/your-username/git-playground.git
cd git-playground
git config --global user.name "your-username"
git config --global user.email "your-email"
  1. Since there is a feature-branch branch in the remote repository, switch to feature-branch, which will cause the local feature-branch to track the feature-branch branch of the remote repository and delete the feature-branch branch in the remote repository:
git checkout feature-branch
git push origin --delete feature-branch
  1. View the trace relationship between local branches and the remote branches they track:
git branch -vv
  1. Switch back to the master branch:
git checkout master
  1. Remove all detached branches from your local repository:
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -D
  1. Verify that the detached branches have been deleted:
git branch

The output should only show the branches that are associated with a specific branch:

* master d22f46b [origin/master] Added file2.txt

Summary

Deleting detached branches is an important step in keeping your Git repository organized and easy to manage. By using the git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -D command, you can easily remove all detached branches from your local repository. This will help you keep your repository clean and make it easier to work with in the future.

Other Git Tutorials you may like