Last active
March 28, 2024 08:44
-
-
Save avramovic/6f0cc3b0bf541ad16084482b25b7e615 to your computer and use it in GitHub Desktop.
Clean up merged Git branches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
if [ ! -d .git ]; then | |
echo "Not a git repository!" | |
exit 1 | |
fi | |
currentBranch=`git status | grep "On branch" | awk '{ print $3 }'` | |
echo "You are on branch:" $currentBranch | |
echo "Please specify branches to skip, separate them with |" | |
echo "(default is: main|master|dev|develop|development|staging|production|release)" | |
read ignore | |
if [ -z $ignore ]; then | |
ignore="main|master|dev|develop|development|staging|production|release" | |
fi | |
echo "Ignoring branches:" $ignore | |
echo "" | |
toRemove=( $( git branch --merged | egrep -v "(^\*|$ignore)" ) ) | |
toRemoveCount=${#toRemove[@]} | |
echo "I will remove the following branches from your local repository:" | |
echo "" | |
printf "%s\n" "${toRemove[@]}" | |
echo "" | |
echo "Total:" $toRemoveCount | |
echo "" | |
echo "Do you want to delete all those branches (local)?" | |
select yn in "Yes" "No"; do | |
case $yn in | |
Yes ) break;; | |
No ) exit;; | |
esac | |
done | |
for (( i=0; i<$toRemoveCount; i++ )); do | |
echo "Deleting branch: ${toRemove[$i]}..." | |
git branch -d ${toRemove[$i]} | |
done | |
echo "" | |
echo "Do you want to delete all those branches from remote?" | |
select yn in "Yes" "No"; do | |
case $yn in | |
Yes ) break;; | |
No ) exit;; | |
esac | |
done | |
echo "" | |
echo "Enter remote name (default=origin)" | |
read remoteName | |
if [ -z $remoteName]; then | |
remoteName="origin" | |
fi | |
echo "" | |
for (( i=0; i<$toRemoveCount; i++ )); do | |
echo "Deleting branch ${toRemove[$i]} from $remoteName..." | |
git push --delete $remoteName ${toRemove[$i]} | |
done | |
echo "" | |
echo "Cleanup..." | |
echo "" | |
git remote prune $remoteName | |
git fetch -p | |
echo "" | |
echo "Voila!" | |
echo "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment