[GIT] Create scripts to delete branches older than N weeks

[GIT] Create scripts to delete branches older than N weeks

I needed a script to clean all my old branches to keep tidy my local repo. Here’s how I did it

First of all create the scripts

nano /home/$USER/scripts/gitclean.sh
Then put this inside the script
#!/bin/bash
for k in $(git branch | sed /\*/d); do
  if [ -z "$(git log -1 --since='6 week ago' -s $k)" ]; then
    git branch -D $k
  fi
done
It deletes branches with no commits in last 6 weeks.

Now save the file and make it executable:

sudo chmod 774 /home/$USER/scripts/gitclean.sh

Last step: create an alias.

nano /home/yourusername/.bash_aliases
Add this row:
alias gitclean="/home/yourusername/scripts/gitclean.sh"

Save the file. Then reload bashrc

source ~/.bashrc

Leave a Reply

Your email address will not be published. Required fields are marked *