sf89 sf89 - 1 year ago 65
Git Question

Delete local Git branches after deleting them on the remote repo

I want to have my local and remote repositories always in sync in terms of branches.

After a Pull Request review on GitHub, I merge and remove my branch there (remote).
How could I fetch this information in my local repository and get Git to remove my local version of the branch as well?

Answer Source

The quick way

git branch --merged | grep -v "\*" | xargs -n 1 git branch -d

NB: if you're not on master, this has the potential to delete the branch. Keep reading for the "better way".

Make sure we keep master

You can ensure that master, or any other branch for that matter, doesn't get removed by greping for more. In that case you would go:

git branch --merged | grep -v "\*" | grep -v "YOUR_BRANCH_TO_KEEP" | xargs -n 1 git branch -d

So if we wanted to keep master, develop and staging for instance, we would go:

git branch --merged | grep -v "\*" | grep -Ev "(\*|master|develop|staging)" | xargs -n 1 git branch -d

Make this an alias

Since it's a bit long, you might want to add an alias to your .zshrc or .bashrc. Mine is called gbpurge (for git branches purge):

alias gbpurge='git branch --merged | grep -Ev "(\*|master|develop|staging)" | xargs -n 1 git branch -d'

Then reload your .bashrc or .zshrc:

. ~/.bashrc


. ~/.zshrc
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download