DEV Community

Ryan, Siu Long Wa
Ryan, Siu Long Wa

Posted on

2 1

Git Prune Local Branches A quick way to prune local branches

When I worked with a lot of features at the same time, it was really common to create a bunch of branches locally.

I felt really annoyed when I run git branch locally... It gives me a ton of legacy branches... This is super annoying especially when I use the tab-complete function.

When I searched for the way to clean up my local environment, it is common that the community will suggest git fetch origin -p. But, in fact, this is just a way to clean up the remote branches cached locally, i.e. the branches you see when you run git branch -r.

It seems that the current git does not implement such handy feature. I have quickly created this snippet in GitHub.

#!/bin/bash -e

git fetch origin -p
REMOTE=$(git branch -r | sed "s/origin\///g")
BRANCHES=$(git branch | awk -F ' +' '! /\(no branch\)/ {print $2}')
for branch in $BRANCHES; do
  if [[ -z $(echo $REMOTE | grep -w $branch) ]]; then
    git branch -D $branch
  fi
done
Enter fullscreen mode Exit fullscreen mode

Ref: https://gist.github.com/RyanSiu1995/da44646f747623d9f51ec52724f16066

Once you create a file with this code, run the following command to put it to your PATH.

chmod 777 git-prune-branches
mv git-prune-branches /usr/local/bin
Enter fullscreen mode Exit fullscreen mode

Enjoy!

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

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

Okay