Skip to content

Instantly share code, notes, and snippets.

@amiralitaheri
Last active June 5, 2021 18:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amiralitaheri/3eb9b403e5a498e6e9cd9587ea91fa3e to your computer and use it in GitHub Desktop.
Save amiralitaheri/3eb9b403e5a498e6e9cd9587ea91fa3e to your computer and use it in GitHub Desktop.
Bash script to delete branches that are merged and stale
#!/usr/bin/env bash
# List of branches that never should be deleted
protected_branches=('v1.7' 'develop' 'master')
echo "Fetching all from remote to ensure everything is up to date..."
git fetch --all
expiration_date=$(date --date="7 days ago")
# The second parameter could be named `isLocal`
if $2; then
branches=$(git --no-pager branch --merged "$1")
else
branches=$(git --no-pager branch -r --merged "$1")
fi
for b in ${branches}; do
last_commit_date=$(git show --format="%ci" "$b" | head -n 1)
# shellcheck disable=SC2076
if [[ ("$expiration_date" > "$last_commit_date") && (! " ${protected_branches[*]} " =~ " ${b} ") ]]; then
echo "Are you sure you want to delete $b? (y/N)?"
read -r choice
case $choice in
y | Y | yes | YES) (! $2 && git push origin --delete "$b") || ( $2 && git branch -d "$b" ) ;;
n | N | no | NO) echo "Skipping $b..." ;;
*) echo "no" ;;
esac
fi
done
echo "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment