Forked from antonio/delete_branches_older_than.sh
Last active
April 10, 2020 13:26
-
-
Save countless-integers/995a10c725ec51da78de to your computer and use it in GitHub Desktop.
Script to delete branches older than a certain date
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
#!/bin/bash | |
dry_run=0 | |
usage() | |
{ | |
cat << EOF | |
usage: $0 [-n] ["string_to_date"] | |
Remove branches older than specified, human-readable date passed as a param | |
Date example: "yesterday", "6 months ago" | |
OPTIONS: | |
-n dry-run, don't delete anything just list commands | |
-h display this help message | |
EOF | |
} | |
if [ -z "$1" ]; then | |
usage | |
exit 3 | |
fi | |
while getopts “n” OPTION | |
do | |
case $OPTION in | |
n) | |
dry_run=1 | |
;; | |
?) | |
usage | |
exit 1 | |
;; | |
esac | |
done | |
shift $((OPTIND-1)) | |
date="$1" | |
if [ -z "$date" ]; then | |
usage | |
exit 2 | |
fi | |
for branch in $(git branch -a | grep origin | grep -vE '(HEAD|master$)' | sed 's/^\s*//' | sed 's/^remotes\///'); do | |
if [[ "$(git log $branch --since "$date" | wc -l)" -eq 0 ]]; then | |
if [[ "$branch" =~ "origin/" ]]; then | |
local_branch_name=$(echo "$branch" | sed -E 's/^(remotes\/)?origin\///') | |
if [[ "$dry_run" -eq 1 ]]; then | |
echo -e $(git log -1 --pretty=format:"%cr" -- $local_branch_name)\\t"# git push origin :$local_branch_name" | |
else | |
git push origin :$local_branch_name | |
fi | |
else | |
if [[ "$dry_run" -eq 1 ]]; then | |
echo -e $(git log -1 --pretty=format:"%cr" -- "$branch")\\t"# git branch -D $branch" | |
else | |
git branch -D $branch | |
fi | |
fi | |
fi | |
done |
Excellent script. Thanks for sharing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exactly what I needed. Thank you :)