Delete remote inactive git branches since a specific date
The following script as it is can be used to delete old branches that have been merged and had no activity since a specific date:
#!/bin/bash
##
# Script to delete remote git branches
##
# Fetch the remote resources
git fetch
# Loop through all remote merged branches
for branch in $(git branch -r --merged | grep -v HEAD | grep -v develop | grep -v master | grep -v master | sed /\*/d); do
if [ -z "$(git log -1 --since='Jun 15, 2020' -s ${branch})" ]; then
echo -e `git show --format="%ci %cr %an" ${branch} | head -n 1` \\t$branch
remote_branch=$(echo ${branch} | sed 's#origin/##' )
# To delete the branches uncomment the bellow git delete command
#git push origin --delete ${remote_branch}
fi
done
A quick rundown of the script:
- First we fetch all of the latest changes with the git fetch command
- Then with a for loop we go through all remote branches
- You can delete the --merged flag so that the script would delete all branches no matter if merged or not
- The --since='Jun 15, 2020' date indicates the date since the branch has been last worked on. The above exmaple will delete all branches that have been idle (eg. no commits or any other activity) since Jun 15, 2020. Update it with the date that matches your needs.