Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastiantecsi/cdf9edb330cc1c77c57728c4f2d5dd1d to your computer and use it in GitHub Desktop.
Save sebastiantecsi/cdf9edb330cc1c77c57728c4f2d5dd1d 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment