Skip to content

Instantly share code, notes, and snippets.

@mrroot5
Last active August 25, 2025 11:35
Show Gist options
  • Select an option

  • Save mrroot5/20857c4f4f5354a6bc3005a4ad7fa5ee to your computer and use it in GitHub Desktop.

Select an option

Save mrroot5/20857c4f4f5354a6bc3005a4ad7fa5ee to your computer and use it in GitHub Desktop.
Clean local git merged or gone branches

Clean local git merged or gone branches

Create a git alias.

Oh My Zsh

They have usefull commands with their git plugin: gbds, gbda and gbgd.

What merged and gone branches means?

  • Merged: branches already merged to the default branch and still in your repository.
  • Gone: branches already merged to the default branch but removed from your repository. Example: automatically delete branches after merging a Pull Request.

How to use it?

The defaul_branch means master, main branch.

  1. git checkout defaul_branch.
  2. git pull origin defaul_branch.
  3. git git cleanup-branches --dry-run defaul_branch.

You also have a --force flag which uses git branch -D instead of git branch -d for branch deletion.

The git alias

git config --global alias.cleanup-branches '!f() { \\\n  DRYRUN=0; FORCE=0; \\\n  # Parse flags\n  while [ $# -gt 0 ]; do \\\n    case \"$1\" in \\\n      --dry-run) DRYRUN=1 ;; \\\n      --force) FORCE=1 ;; \\\n      *) break ;; \\\n    esac; \\\n    shift; \\\n  done; \\\n# Require BASE\n  if [ -z \"$1\" ]; then echo \"Usage: git cleanup-branches [--dry-run] [--force] <base> [excludes...]\"; exit 1; fi; \\\n  BASE=$1; shift; \\\n  # Select delete command\n  if [ $FORCE -eq 1 ]; then DELCMD=\"git branch -D\"; else DELCMD=\"git branch -d\"; fi; \\\n  git fetch -p; \\\n  if [ $DRYRUN -eq 1 ]; then \\\n    echo \"Would delete merged branches:\"; \\\n    git branch --merged \"$BASE\" | grep -v \"$BASE\"; \\\n    echo \"Would delete gone branches:\"; \\\n    git branch -vv | awk \"/: gone]/{print \\$1}\"; \\\n  else \\\n    git branch --merged \"$BASE\" | grep -v \"$BASE\" | xargs -r $DELCMD; \\\n    git branch -vv | awk \"/: gone]/{print \\$1}\" | xargs -r $DELCMD; \\\n  fi; \\\n}; f'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment