Skip to content

Instantly share code, notes, and snippets.

@goncalossilva
Last active April 8, 2021 15:25
Show Gist options
  • Save goncalossilva/47003db3da2175829511c254be5cea16 to your computer and use it in GitHub Desktop.
Save goncalossilva/47003db3da2175829511c254be5cea16 to your computer and use it in GitHub Desktop.
Autoremove deleted and merged branches, locally and remotely.
[alias]
autoremove = "!f() { \
whitelist=\"master|dev|legacy\"; \
git fetch --prune; \
if [ -z \"$1\" ]; then \
list=$(git branch --merged | egrep -v \"(^\\*|$whitelist)\") && \
cmd='echo \"$list\" | xargs -n 1 git branch -d'; \
else \
list=$(git branch -r --merged | grep \"$1\" | egrep -v \"(>|$whitelist)\") && \
cmd='echo \"$list\" | cut -d'/' -f2- | xargs -n 1 git push \"$1\" --delete'; \
fi; \
echo \"On branch $(git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \\(.*\\)/\\1/'). \"; echo \"\"; \
if [ -z \"$list\" ]; then \
echo \"No branches to remove.\"; \
else \
echo \"Branches to remove:\"; echo \"$list\"; echo \"\"; \
read -p 'Press enter to continue'; echo \" \"; \
eval $cmd; \
fi \
}; f"
autoremoveall = "!git remote | xargs -n 1 git autoremove; git autoremove"
@goncalossilva
Copy link
Author

goncalossilva commented Nov 9, 2017

Git autoremove

Git alias to remove deleted and merged branches. It works locally, with any specific remote or both.

It should be added to your .gitconfig aliases. You can inline as displayed above, or create a git-autoremove.sh script, add it to your path, and call it like so: autoremove = "!sh git-autoremove.sh".

Usage

First of all, make sure to edit the whitelist to match your own protected branches. Afterwards, go forth and clean up.

To delete local branches that have been deleted or merged:
git autoremove

To delete branches from a specific remote that have been deleted or merged:
git autoremove origin # or any other remote

Most often than not, you'll want to delete all deleted / merged branches, regardless if local or belonging to any remote:
git autoremoveall

Demo

git-autoremove

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