Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save countless-integers/995a10c725ec51da78de to your computer and use it in GitHub Desktop.
Save countless-integers/995a10c725ec51da78de to your computer and use it in GitHub Desktop.
Script to delete branches older than a certain date
#!/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
@lelandcope
Copy link

Exactly what I needed. Thank you :)

@djpentz
Copy link

djpentz commented Jul 28, 2016

Excellent script. Thanks for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment