Last Updated: June 02, 2023
·
41.72K
· niklongstone

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:

  1. git branch -r: lists remote branches
  2. awk '{print $1}': prettify the output of previous command
  3. egrep -v -f /dev/fd/0 <(git branch -vv | grep origin): print a difference between remote and local branches
  4. awk '{print $1}': prettify the previous
  5. 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:

Remove all your local git branches but keep master

4 Responses
Add your response

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?

over 1 year ago ·

HI, thanks for the suggestion, I've added the explaination on the tip.

over 1 year ago ·

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

8 months ago ·

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'

8 months ago ·