Last active
January 26, 2026 23:29
-
-
Save eduardoarandah/c0d2e222c73a56869a9d01bd8714bef1 to your computer and use it in GitHub Desktop.
Git branch cleanup function for zsh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Git branch cleanup function for zsh | |
| git_cleanup_merged_branches() { | |
| # Require main branch parameter | |
| if [[ -z "$1" ]]; then | |
| echo "Usage: git_cleanup_merged_branches <main-branch>" | |
| return 1 | |
| fi | |
| local main_branch="$1" | |
| # Check if we're currently on the main branch - must be on main to see what's merged into it | |
| local current_branch=$(git branch --show-current) | |
| if [[ "$current_branch" != "$main_branch" ]]; then | |
| echo "Error: Must be on '$main_branch' branch. Currently on '$current_branch'." | |
| return 1 | |
| fi | |
| # Get all branches merged into current branch, excluding main/master/dev | |
| local branches=$(git branch --merged | grep -vE "^\*|^\s*(main|master|dev|$main_branch)\s*$" | sed 's/^[ *]*//') | |
| if [[ -z "$branches" ]]; then | |
| echo "No merged branches to clean up." | |
| return 0 | |
| fi | |
| echo "Merged branches to review:\n" | |
| echo "$branches" | sed 's/^/ - /' | |
| echo "\ny/n: delete merged branches?\n" | |
| echo "$branches" | xargs --interactive --max-args=1 git branch --delete | |
| echo "\nBranch cleanup complete." | |
| } | |
| # Git remote branch cleanup function for zsh | |
| git_cleanup_merged_branches_remote() { | |
| # Require main branch parameter | |
| if [[ -z "$1" ]]; then | |
| echo "Usage: git_cleanup_merged_branches_remote <main-branch>" | |
| return 1 | |
| fi | |
| local main_branch="$1" | |
| # Fetch latest remote info and prune deleted branches | |
| git fetch --prune | |
| # Get remote branches merged into origin/$main_branch | |
| local branches=$(git branch -r --merged origin/$main_branch | grep 'origin/' | grep -vE "origin/(main|master|dev|HEAD|$main_branch)" | sed 's|origin/||' | sed 's/^[ ]*//') | |
| if [[ -z "$branches" ]]; then | |
| echo "No merged remote branches to clean up." | |
| return 0 | |
| fi | |
| echo "Merged remote branches on origin to review:\n" | |
| echo "$branches" | sed 's/^/ - /' | |
| echo "\ny/n: delete merged remote branches from origin?\n" | |
| echo "$branches" | xargs --interactive --max-args=1 git push origin --delete | |
| echo "\nRemote branch cleanup complete." | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment