BASH
Clean Up Merged and Remote-Deleted Local Git Branches
Keep your local Git repository clean and organized by automatically deleting merged branches that no longer exist on the remote, improving developer hygiene.
#!/bin/bash
# --- Configuration ---
MAIN_BRANCH="main" # Or 'master', depending on your repository
REMOTE_NAME="origin"
# --- Script Logic ---
echo "Fetching remote branches and pruning local refs that no longer exist on remote..."
git fetch "$REMOTE_NAME" --prune
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo "Finding and deleting merged local branches (excluding $MAIN_BRANCH and current branch)..."
git branch --merged "$MAIN_BRANCH" | grep -v "$MAIN_BRANCH" | grep -v "$CURRENT_BRANCH" | xargs -n 1 git branch -d
echo "Local Git branches cleaned up."
How it works: This script helps maintain a tidy local Git repository by cleaning up stale branches. It starts by fetching from the remote and pruning local references that no longer track a remote branch. Then, it identifies and deletes all local branches that have been merged into your main branch, safely preserving your main branch and the currently active branch.