Last Updated: October 04, 2020
·
35.5K
· 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

2 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 ·