Last active
December 14, 2019 08:01
-
-
Save ocavue/377be22d1c88a34b21940747a810718c to your computer and use it in GitHub Desktop.
Clean old and useless remote git branches (Tested with Git v2.21.0 on macOS 10.14 and Git v2.7.4 on Ubuntu 16.04)
This file contains hidden or 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 | |
| # The number of branchs you want to keep | |
| KEEP=100 | |
| git fetch --all --prune -q | |
| all_remote_branchs_num=$(git branch -r | wc -l | awk '{print $1}') | |
| to_delete_remote_branchs_num=$(($all_remote_branchs_num - $KEEP)) | |
| to_delete_remote_branchs=$(git for-each-ref --sort=committerdate --format="%(refname:short)" 'refs/remotes' | head -n $to_delete_remote_branchs_num ) | |
| echo '' | |
| echo "Going to delete $to_delete_remote_branchs_num branchs from $all_remote_branchs_num branchs" | |
| echo 'The first branch to delete is:' | |
| # Some old version git doesn't have --pretty="%S", so I have to use ${branch} | |
| branch=$(echo "$to_delete_remote_branchs" | head -n 1) | |
| git show --no-notes --no-patch --pretty="%Cred%h %Cgreen%aI %C(yellow)${branch} %C(cyan)%an %C(auto)- %s" $branch | |
| echo 'The last branch to delete is:' | |
| branch=$(echo "$to_delete_remote_branchs" | tail -n 1) | |
| git show --no-notes --no-patch --pretty="%Cred%h %Cgreen%aI %C(yellow)${branch} %C(cyan)%an %C(auto)- %s" $branch | |
| read -p "Press ENTER to continue. Press CTRL-C to exit. " | |
| echo '' | |
| for branch in $to_delete_remote_branchs | |
| do | |
| git show --no-notes --no-patch --pretty="Deleting %Cred%h %Cgreen%aI %C(yellow)${branch} %C(cyan)%an %C(auto)- %s" $branch | |
| ref=$(echo $branch | cut -d '/' -f '2-') # Remove 'origin/' from $branch | |
| remote=$(echo $branch | cut -d '/' -f '1') | |
| # Example: $branch is 'origin/release/login'; $ref is 'release/login'; $remote is 'origin' | |
| git push $remote --delete $ref -q | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment