Remove local branches no longer on remote
Is there a simple way to delete all local branches which do not have a remote equivalent?
Example:
Branches (local and remote)
Locally, I only have a master branch. Now I need to work on bug-fix-a, so I check it out, work on it, and push changes to the remote. Next I do the same with bug-fix-b.
Branches (local and remote)
Now I have local branches master, bug-fix-a, bug-fix-b. The Master branch maintainer will merge my changes into master and delete all branches he has already merged.
So the current state is now:
Branches (local and remote)
Now I would like to call some command to delete branches (in this case bug-fix-a, bug-fix-b), which are no longer represented in the remote repository.
It would be something like the existing command git remote prune origin
, but more like git local prune origin
.
git remote prune origin
prunes tracking branches not on the remote.
git branch --merged
lists branches that have been merged into the current branch.
xargs git branch -d
deletes branches listed on standard input.
Be careful deleting branches listed by git branch --merged
. The list could include master
or other branches you'd prefer not to delete.
To give yourself the opportunity to edit the list before deleting branches, you could do the following in one line:
git branch --merged >/tmp/merged-branches && vi /tmp/merged-branches && xargs git branch -d </tmp/merged-branches
After the command
git fetch -p
removes the remote references, when you run
git branch -vv
it will show 'gone' as the remote status. For example,
$ git branch -vv
master b900de9 [origin/master: behind 4] Fixed bug
release/v3.8 fdd2f4e [origin/release/v3.8: behind 2] Fixed bug
release/v3.9 0d680d0 [origin/release/v3.9: behind 2] Updated comments
bug/1234 57379e4 [origin/bug/1234: gone] Fixed bug
So you can write a simple script to remove local branches that have gone remotes:
git fetch -p && for branch in `git branch -vv | grep ': gone]' | awk '{print $1}'`; do git branch -D $branch; done
Most of these answers do not actually answer the original question. I did a bunch of digging and this was the cleanest solution I found. Here is a slightly more thorough version of that answer:
git checkout master
git fetch -p && git branch -vv | awk '/: gone]/{print $1}' | xargs git branch -d
git fetch -p && git branch -vv | awk '/: gone]/{print $1}' | xargs git branch -d
Explanation:
Works by pruning your tracking branches then deleting the local ones that show they are "gone" in git branch -vv
.
Notes:
If your language is set to something other than English you will need to change gone
to the appropriate word. Branches that are local only will not be touched. Branches that have been deleted on remote but were not merged will show a notification but not be deleted on local. If you want to delete those as well change -d
to -D
.
上一篇: 从Git中删除旧的远程分支
下一篇: 不再在远程删除本地分支