How to cleanup your old Git branches

bdelespierre profile image Benjamin Delespierre ・1 min read


git branch -a | grep remotes/origin | sed 's/\s*remotes\/origin\///' | grep -v master | grep -v develop | xargs -n 1 -P 8 git push origin --delete

Bash to the rescue

Step 1: list the branches

git branch -a

Step 2: filter only the remote branches

... | grep remotes/origin

Step 3: remove the prefix

... | sed 's/\s*remotes\/origin\///'

Step 4: exclude branches you want to keep!

... | grep -v master | grep -v develop 

Step 5: destroy everything!

... | xargs -n 1 -P 8 git push origin --delete

Xargs options:

  • -n 1 means one after another (or one per-process)
  • -P 8 means create 8 processes (8x time faster!)

Tell your friends

Now you can tell your coworkers to:

git fetch --prune

on their machine to purge the branches you've just deleted from origin.


Bonus: to check which branches will actually be deleted you can simply replace git push origin --delete with echo.

Leave a comment below to tell me what you think or if you have a question

Posted on by:

bdelespierre profile

Benjamin Delespierre


CTO at AddWorking, I write Laravel snippets all the time


markdown guide