Auto-Delete Old Git Branches

Old Git branches that are already merged can very quickly clutter your local repository. This can make it more difficult to find active branches you are working on. With a simple shell script we can clean up these old branches.

git checkout "$(basename "$(git symbolic-ref --short refs/remotes/origin/HEAD)")"
git pull
git fetch -p

git branch -vv |
	grep 'origin/.*: gone]' |
	grep -v '^+' |
	awk '{print $1}' |
	xargs git branch -D

This script has three main steps:

  1. Checkout the default branch (e.g. main or master)
  2. Fetch all origin branches pruning the branches no longer present on the origin
  3. Deletes local branches which were deleted on the origin

I use this command on a daily basis as a replacement for the typical workflow of checking out the default branch and pulling changes. It’s only one script I have to run, and it keeps my workspace tidy at the same time!