Skip to content

Instantly share code, notes, and snippets.

@sergekukharev
Created May 1, 2025 12:39
Show Gist options
  • Save sergekukharev/cc0389552fd7c3b968e6771682329d63 to your computer and use it in GitHub Desktop.
Save sergekukharev/cc0389552fd7c3b968e6771682329d63 to your computer and use it in GitHub Desktop.
This script allows to delete branches that were already merged and clean up your local setup
#!/bin/bash
# Switch to main branch
git checkout main
git pull
echo "Fetching latest changes from origin..."
git fetch -p
echo "=== Local branches that will be deleted ==="
git branch --merged | grep -v "\*" | grep -v main | grep -v master
echo ""
echo "=== Remote branches that will be deleted ==="
git branch -r --merged | grep -v 'origin/main' | grep -v 'origin/master' | grep origin | sed 's/origin\///'
read -p "Do you want to proceed with deletion? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
# Delete local branches
echo "Deleting local merged branches..."
git branch --merged | grep -v "\*" | grep -v main | grep -v master | xargs git branch -d
# Delete remote branches
echo "Deleting remote merged branches..."
git branch -r --merged | grep -v 'origin/main' | grep -v 'origin/master' | grep origin | sed 's/origin\///' | xargs -I{} git push origin --delete {}
else
echo "Operation cancelled."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment