Skip to content

Instantly share code, notes, and snippets.

@apgapg
Created April 17, 2024 06:00
Show Gist options
  • Save apgapg/ff517987321398144bf0378d31778684 to your computer and use it in GitHub Desktop.
Save apgapg/ff517987321398144bf0378d31778684 to your computer and use it in GitHub Desktop.
Delete old Git branches from remote
#!/bin/bash
# Set the cutoff date 6 months ago
cutoff_date=$(date -d "6 months ago" +%Y-%m-%d)
# Fetch all branches from the remote repository
git fetch --prune
# Iterate over each remote branch
for branch_with_origin in $(git branch -r --format='%(refname:short)'); do
# Remove "origin/" prefix from the branch name
branch=$(echo "$branch_with_origin" | sed 's/^origin\///')
# Get the commit date of the branch
commit_date=$(git log -1 --format=%cd --date=short "$branch_with_origin")
# Check if the commit date is older than the cutoff date
if [[ $commit_date < $cutoff_date ]]; then
# Delete the remote branch
if git push origin --delete "$branch"; then
echo "Deleted remote branch: $branch"
else
echo "Failed to delete remote branch: $branch"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment