Here’s a simple script I use to clean all local merged local branches, and also any stale references to remote branches. The latter will impact tab completion for example when you
git checkout <tab> and see branches that don’t exist in
- Create a script in your path called
chmod +x git-clean-unused-branchesit
Now you have the
git clean-unused-branches command.
#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' # Delete any branches that have been merged. # +e to allow grep to fail without a non-zero exit code there are no matches. # Exclude branches called "master" and the current branch (prefixed with "* ") set +e LOCAL_BRANCHES=$(git branch --merged master | grep -v -e 'master' -e '\*' | tr -d ' ') set -e if [[ -n "$LOCAL_BRANCHES" ]]; then for BRANCH in $LOCAL_BRANCHES; do git branch -d "$BRANCH" done fi # Prune any stale remote references git remote prune origin