DEV Community

Benjamin Delespierre
Benjamin Delespierre

Posted on

How to cleanup your old Git branches

TL;DR

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
Enter fullscreen mode Exit fullscreen mode

Bash to the rescue

Step 1: list the branches

git branch -a
Enter fullscreen mode Exit fullscreen mode

Step 2: filter only the remote branches

... | grep remotes/origin
Enter fullscreen mode Exit fullscreen mode

Step 3: remove the prefix

... | sed 's/\s*remotes\/origin\///'
Enter fullscreen mode Exit fullscreen mode

Step 4: exclude branches you want to keep!

... | grep -v master | grep -v develop 
Enter fullscreen mode Exit fullscreen mode

Step 5: destroy everything!

... | xargs -n 1 -P 8 git push origin --delete
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Enjoy


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

Top comments (2)

Collapse
 
jakeerc profile image
Jakeer

Salam,
Thanks

Collapse
 
bdelespierre profile image
Benjamin Delespierre

Salaam. Most welcome.