
Over time, your local git branches list can become overwhelming, particularly if you develop on a single branch, generate a pull request, merge it into the main branch, and then remove the remote git branch once it has been merged. After the branch is removed from the remote repository, there is no need to keep it on your local machine.
The following command will delete all local branches that have been merged into the main branch. If your git trunk branch is not named main or you wish to remove all branches that have been merged into a branch other than main, simply modify the two instances of the word main in the command to reflect the name of your branch.
Remove local merged git branches
To remove all the local branches, which are merged into the main branch, navigate to the root of the repository and run the following git commands,
- Fetch the latest updates from the git repository
git fetch
- See the list of local branches available in the repository
git branch
- Delete all local branches that have been merged to main branch
git branch --merged main | grep -v "^\* main" | xargs -n 1 -r git branch -d
The above steps will remove all the branches from the local computer, which are already merged in main branch.
Remove local noexistent git branches
Similarly, to remove all the branches from the local computer, which are deleted or not exists on the remote repository, navigate to the root of the repository and run the following git commands,
- Fetch the latest updates from the git repository
git fetch
- See the list of local branches available in the repository
git branch
- Delete all local branches that have been merged to main branch
git branch -vv | grep ': gone]' | grep -v '\*' | awk '{ print $1; }' | xargs -r git branch -D