Skip to content

Instantly share code, notes, and snippets.

@AvnerCohen
Forked from antonio/delete_branches_older_than.sh
Last active September 23, 2024 23:59
Show Gist options
  • Save AvnerCohen/b8a40c62f8097d8c7b14 to your computer and use it in GitHub Desktop.
Save AvnerCohen/b8a40c62f8097d8c7b14 to your computer and use it in GitHub Desktop.
Script to delete branches older than 6 months old, ignore local vs remote errors.
#!/bin/sh
ECHO='echo '
for branch in $(git branch -a | sed 's/^\s*//' | sed 's/^remotes\///' | grep -v 'master$'); do
if [[ "$(git log $branch --since "6 months ago" | wc -l)" -eq 0 ]]; then
if [[ "$DRY_RUN" = "false" ]]; then
ECHO=""
fi
local_branch_name=$(echo "$branch" | sed 's/remotes\/origin\///')
$ECHO git branch -d "${local_branch_name}"
$ECHO git push origin --delete "${local_branch_name}"
fi
done
@sreenivasuluchennappa
Copy link

above script i try to run it display branch name to delete and also to push that branch name

Note Issue: In that Repository not reflected , delete branch 6 months old still display in repository
DeleteBranch

Ran the script file, it ran for long time and see the commands were executed but then closed by itself and I see the branched still there in remote?

@AvnerCohen
Copy link
Author

  1. Note the "DRY_RUN" argument you need to set it to false to actually delete.
  2. I see branch names with white spaces, added a minor fix for that.

@njames
Copy link

njames commented Jun 15, 2021

I like this script but it seems to pick up directories and files ...

    
    ECHO='echo ';
    for branch in $(git branch -a | sed 's/^\s*//' | sed 's/^remotes\///' | grep -v 'main$\|develop$'); do
      if [[ -f "$branch" ]]; then 
        $ECHO $branch;
      fi
    done

I added a directory and file check


  ECHO='echo ';
  for branch in $(git branch -a | sed 's/^\s*//' | sed 's/^remotes\///' | grep -v 'main$\|develop$'); do
    if ! ( [[ -f "$branch" ]] || [[ -d "$branch" ]] ); then 
      $ECHO $branch;
    fi
  done

@njames
Copy link

njames commented Jun 15, 2021

my full script is here ... note I want to exclude main and develop

https://gist.github.com/njames/88425c2771a14c5fe1220c19a16bdac6

@kapilLaad18
Copy link

this script is not deleting the branches from remote repo, i ran it's executed completely and then count is same on remote branch

@jjb
Copy link

jjb commented Sep 23, 2024

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