Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Script to delete branches older than 6 months old, ignore local vs remote errors.
ECHO='echo '
for branch in $(git branch -a | sed 's/^\s*//' | sed 's/^remotes\///' | grep -v 'main$\|develop$'); do
if ! ( [[ -f "$branch" ]] || [[ -d "$branch" ]] ) && [[ "$(git log $branch --since "1 month ago" | wc -l)" -eq 0 ]]; then
if [[ "$DRY_RUN" = "false" ]]; then
local_branch_name=$(echo "$branch" | sed 's/remotes\/origin\///')
$ECHO git branch -d "${local_branch_name}"
$ECHO git push origin --delete "${local_branch_name}"
Copy link

devhpes commented Jul 22, 2022

Yes It can be added.

Copy link

Will this detect any recent updates to the branches or will it base the age by the date the branch was created?

Copy link

vitorhugomattos commented May 11, 2023

this will delete based on the latest commit timestamp (note the --since flag). if you want to delete based on branch creation date you should change the flag to --before.

Copy link

Great. Thanks

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