Skip to content

Instantly share code, notes, and snippets.

@gmolveau
Created July 7, 2022 12:50
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 gmolveau/3f9f80086cab0d4026fb208631f0d7df to your computer and use it in GitHub Desktop.
Save gmolveau/3f9f80086cab0d4026fb208631f0d7df to your computer and use it in GitHub Desktop.
git-rimraf : delete branches that don't exist on remote
#!/bin/bash
git fetch -p && (git for-each-ref --format='%(if:equals=[gone])%(upstream:track)%(then)%(refname:short)%(end)' refs/heads; git for-each-ref --format "%(refname:short) %(upstream)" refs/heads | awk '{if (!$2) print $1;}') | grep -E -v 'master|main|develop' | xargs echo git branch -D
# explanation
# - `git fetch -p` : fetch branches that no longer exist on remote
# - `git for-each-ref --format='%(if:equals=[gone])%(upstream:track)%(then)%(refname:short)%(end)' refs/heads` : list all branches that no longer exist on remote
# - `git for-each-ref --format "%(refname:short) %(upstream)" refs/heads | awk '{if (!$2) print $1;}'` : list all branches without a remote
# - `grep -E -v 'master|main|develop'` : remove master, main, develop branches from the results
# - `xargs echo git branch -D` : print the commande to delete those branches (remove echo if you want to exec this command directly)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment