BASH
Clean Up Stale Git Branches
Automate the deletion of local Git branches that have already been merged into your main development branch, helping to keep your repository clean and manageable.
#!/bin/bash
# Default main branch name (can be 'main' or 'master')
MAIN_BRANCH="main"
# Check if a different branch name is provided as an argument
if [ -n "$1" ]; then
MAIN_BRANCH="$1"
fi
echo "Fetching latest from origin..."
git fetch origin --prune
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo "Listing merged branches (excluding ${MAIN_BRANCH} and current branch):"
# Get a list of merged branches, excluding main and current branch
MERGED_BRANCHES=$(git branch --merged "$MAIN_BRANCH" | grep -v "$MAIN_BRANCH" | grep -v "$CURRENT_BRANCH" | sed 's/^\* //g' | sed 's/^ //g')
if [ -z "$MERGED_BRANCHES" ]; then
echo "No merged branches to delete."
else
echo "$MERGED_BRANCHES"
read -p "Do you want to delete these branches? (y/N): " CONFIRM
if [[ "$CONFIRM" =~ ^[yY]$ ]]; then
echo "$MERGED_BRANCHES" | xargs -n 1 git branch -d
echo "Deleted merged branches."
else
echo "Deletion cancelled."
fi
fi
How it works: This script automates the process of cleaning up local Git branches that have already been merged into the `main` branch (or a specified alternative like `master`). It first fetches from origin to ensure the branch status is up-to-date, then lists all merged branches, excluding the `main` and current active branch. Finally, it prompts the user for confirmation before deleting them, keeping the local repository tidy and organized.