Git - remove local branches not on remote
git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk '{print $1}' | xargs git branch -d
Commands explaination:
-
git branch -r
: lists remote branches -
awk '{print $1}'
: prettify the output of previous command
-
egrep -v -f /dev/fd/0 <(git branch -vv | grep origin)
: print a difference between remote and local branches
-
awk '{print $1}'
: prettify the previous
-
xargs git branch -d
: removes local branches found at point 3
Using the commands omitting the last one, will give you a preview on what will be removed.
If you enjoyed the tip, follow me on: https://twitter.com/niklongstone
Related protips:
Written by Nicola Pietroluongo
Related protips
4 Responses
Can you give some details of what it's doing? What are the remote names? I see it's origin. Does it remove local branches not on origin? What if I have 2 remotes, origin and upstream and I want to remove all the branches from origin that are not on upstream?
HI, thanks for the suggestion, I've added the explaination on the tip.
This is very helpful, but I am getting this error. error: The branch 'feature/lskey-V2.14.4.6' is not fully merged, I had to change the -d to a force drop -D
here are some git bash aliases if anyone needs them, adjusted to work as an aliases
alias removelocaldry='function _removelocaldry(){ git branch -r | awk "{print \$${1:-1}}" | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk "{print \$${1:-1}}"; }; _removelocaldry'
alias removelocal='function _removelocal(){ git branch -r | awk "{print \$${1:-1}}" | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk "{print \$${1:-1}}" | xargs git branch -D; }; _removelocal'