Delete Merged Git Branches

Keeping your Git branches clean in your local repo is very helpful to make it easy to switch between branches you are currently working on. The last thing you want is a bunch of old branches that have already been merged showing in your list of branches when running git checkout.

To solve this problem, I created a simple shell script that will run the following steps:

  1. Checkout the default branch (e.g., main)
  2. Pull the latest changes
  3. Delete local branches that have been deleted on the remote
#!/usr/bin/env bashset -euo pipefailgit checkout $(basename $(git symbolic-ref --short refs/remotes/origin/HEAD))git pullgit fetch -p# Delete local branches that have been deleted on remotegit branch -vv |	grep 'origin/.*: gone]' |	grep -v '^+' |	awk '{print $1}' |	xargs git branch -D