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:
- Checkout the default branch (e.g.,
main
) - Pull the latest changes
- Delete local branches that have been deleted on the remote
#!/usr/bin/env bash
set -euo pipefail
git checkout $(basename $(git symbolic-ref --short refs/remotes/origin/HEAD))
git pull
git fetch -p
# Delete local branches that have been deleted on remote
git branch -vv |
grep 'origin/.*: gone]' |
grep -v '^+' |
awk '{print $1}' |
xargs git branch -D