Skip to content

Instantly share code, notes, and snippets.

@mbrowniebytes
Created April 24, 2023 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbrowniebytes/85a1c9b5a7c39cbdcb701c42c1098ef9 to your computer and use it in GitHub Desktop.
Save mbrowniebytes/85a1c9b5a7c39cbdcb701c42c1098ef9 to your computer and use it in GitHub Desktop.
Delete merged local branches older than N days
#!/bin/bash
# delete merged local branches
days=90
found=0
# preview
# git branch --merged | grep -v -E "\\*|\bmaster\b|\bmain\b|\bdevelopment\b" | xargs -r -n 1
# list branches merged
# git branch --merged
# https://git-scm.com/docs/git-branch
# exclude master, main, development
# grep -v -E "\\*|\bmaster\b|\bmain\b|\bdevelopment\b"
# -v, --invert-match select non-matching lines
# -E, --extended-regexp \b word boundaries
# https://www.man7.org/linux/man-pages/man1/grep.1.html
# xargs -r -n 1
# -n max-args, --max-args=max-args; exit if greater
# -r, --no-run-if-empty; do not run if no results
# https://www.man7.org/linux/man-pages/man1/xargs.1.html
# git log -1 --since="$days days ago" -s $k
# gti log, one line, since $days days ago, for branch $k
# https://www.git-scm.com/docs/git-log
# delete branch
# git branch -d $k
# https://git-scm.com/docs/git-branch
echo "branches older than $days days:"
for k in $(git branch --merged | grep -v -E "\\*|\bmaster\b|\bmain\b|\bdevelopment\b" | xargs -r -n 1); do
if [[ ! $(git log -1 --since="$days days ago" -s $k) ]]; then
echo $k
(( found++ ))
fi
done
if [[ $found -eq 0 ]]; then
echo "no branches found"
exit 0
fi;
read -s -n 1 -p "press any key to delete $found branches older than $days days . . ."
echo ""
# run
for k in $(git branch --merged | grep -v -E "\\*|\bmaster\b|\bmain\b|\bdevelopment\b" | xargs -r -n 1); do
if [[ ! $(git log -1 --since="$days days ago" -s $k) ]]; then
git branch -d $k
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment