DEV Community

Benjamin Delespierre
Benjamin Delespierre

Posted on

9 6

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (2)

Collapse
 
jakeerc profile image
Jakeer

Salam,
Thanks

Collapse
 
bdelespierre profile image
Benjamin Delespierre

Salaam. Most welcome.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay