Last active
August 27, 2022 04:57
-
-
Save fahimalizain/04742b87e6132a0c783b92bbb0ef80e8 to your computer and use it in GitHub Desktop.
A simple script that deletes Git Branches older than specific days
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
PWD=$(pwd) | |
DAYS_THRESHOLD=5 | |
# Check if in Git Repository | |
if [ ! "$(git rev-parse --is-inside-work-tree 2>/dev/null)" = "true" ]; then | |
echo "This is not a git repository!" | |
exit 1 | |
fi | |
# Get list of branches and make it an Array | |
BRANCHES="$(git branch --format='%(refname:short)')" | |
BRANCHES=(${BRANCHES//$'\n'/ }) | |
# Loop through each branch and prompt user | |
for b in "${BRANCHES[@]}" | |
do | |
# Get the last commit date from the branch git-log | |
LAST_COMMIT_DATE=$(git log $b -1 --format="%cd" --date=iso) | |
# Calculate its age in DAYS | |
let DIFF=($(date +%s)-$(date +%s --date="$LAST_COMMIT_DATE"))/86400 | |
echo -e "- ${YELLOW} $b ${DARK_GRAY}($DIFF Days Old)${NC}" | |
# Check threshold, get confirmation from User & delete! | |
if [ "$DIFF" -gt "$DAYS_THRESHOLD" ]; then | |
read -p "Delete ? " yn | |
case $yn in | |
[Yy]* ) | |
git branch -D $b | |
echo "" | |
;; | |
*) | |
echo "Skipped" | |
;; | |
esac | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment