The remote tracking branches may still exist in your local after a feature branch is merged(to a main branch) and deleted from remote (the normal pull request workflow)
The corresponding local branches too may exist and pile up locally, if you are too lazy to delete them.
Is there a way to use the information available on remote (say only main branch exists on remote (the longest living branch.)) -
I want to:
- Get rid of the remote tracking branches that my local still shows (although the actual remote branches are now deleted, probably because they were merged-and-then-deleted)
- Get rid of local branches that I was too lazy to delete - and which have been merged on remote already (and deleted - dont exist on remote anymore because merged)
Everything in above screenshot in 1 (except remotes/origin/main
) - is non existent in reality on remote. So want to delete these tracking branches (they start with remote/...
) from my local too.
Everything under 2 (except main
) is branches that I sent to remote, created MR, got merged remotly, and I was lazy/forgot to delete from local. Most likely wont be using them ever (unless some rework is needed - but that should anyway happen as new feature/fix). So its safe to delete because its content is already merged to a long living branch - thats why it was delted on remote! Just want to do the same but now.
Found this SO has some great ways discussed to do this.
And also this improved solution.
# Step 1
git remote prune origin
# Step 2
git branch --merged
# better, if main is the long living branch name that appears in when doing `git branch --merged` then to avoid deleting `main` branch:
git branch --merged main | grep -v '^[ *]*main$' | xargs git branch -d
# Step 3
xargs git branch -d
If you want to delete all local branches that are already merged into master, you can use the following command:
git branch --merged master | grep -v '^[ *]*master$' | xargs git branch -d
If you are using main
as your master branch, you should modify the command accordingly:
git branch --merged main | grep -v '^[ *]*main$' | xargs git branch -d