Introduction
🧑💻 New to Git or LabEx? We recommend starting with the Quick Start with Git course.
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.
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".
- 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"
- Since there is a
feature-branchbranch in the remote repository, switch tofeature-branch, which will cause the localfeature-branchto track thefeature-branchbranch of the remote repository and delete thefeature-branchbranch in the remote repository:
git checkout feature-branch
git push origin --delete feature-branch
- View the trace relationship between local branches and the remote branches they track:
git branch -vv
- Switch back to the
masterbranch:
git checkout master
- Remove all detached branches from your local repository:
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -D
- 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.