BASH
Automate Git Branch Cleanup
Streamline your Git workflow with a bash script that automatically deletes merged local branches that are no longer needed, helping to keep your repository tidy.
#!/bin/bash
# Ensure we are in a Git repository
if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
echo "Error: Not a Git repository."
exit 1
fi
# Fetch latest remote changes
git fetch --prune
# Get current branch
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo "Deleting merged local branches (excluding current: $CURRENT_BRANCH):"
# Delete local branches that have been merged into the current branch and are not the current branch
git branch --merged | grep -v "$CURRENT_BRANCH" | xargs -n 1 git branch -d
# Alternative for more aggressive cleanup (deletes even unmerged local branches that have no upstream)
# echo -e "
Alternatively, to delete local branches that are no longer tracked remotely (DANGEROUS if you have unpushed work):"
# git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -d
echo -e "
Branch cleanup complete."
How it works: This script automates the cleanup of local Git branches. It first ensures it's run within a Git repository, fetches the latest remote changes, and then identifies and deletes local branches that have already been merged into the current branch (e.g., `main` or `develop`). This helps developers maintain a clean local repository by removing stale branches.