Skip to content

Instantly share code, notes, and snippets.

@jfacoustic
Created August 5, 2025 20:18
Show Gist options
  • Select an option

  • Save jfacoustic/bc787238ea6f5470dbf4e4ac4c2f1272 to your computer and use it in GitHub Desktop.

Select an option

Save jfacoustic/bc787238ea6f5470dbf4e4ac4c2f1272 to your computer and use it in GitHub Desktop.
Remove old git branches merged into protected branches
#!/usr/bin/env bash
branches=$(git branch --format="%(refname:short)")
branches_to_delete=()
current_branch=$(git rev-parse --abbrev-ref HEAD)
protected_branches=("main" "master" "develop" "staging" "$current_branch")
echo
echo "Merged Branches:"
for branch in $branches; do
[[ " ${protected_branches[*]} " == *" $branch "* ]] && continue
if git log --oneline | grep -q $branch; then
branches_to_delete+=($branch)
echo "- $branch"
fi
done
echo
for branch in "${branches_to_delete[@]}"; do
read -p "Do you want to delete the branch '$branch'? [y/N] " confirm
if [[ $confirm =~ ^[Yy]$ ]]; then
git branch -D "$branch"
echo "Deleted branch '$branch'."
else
echo "Skipped branch '$branch'."
fi
echo
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment