Skip to content

Instantly share code, notes, and snippets.

@62mkv
Last active October 12, 2022 09:19
Show Gist options
  • Save 62mkv/af3ce50d1b3a5246d38b to your computer and use it in GitHub Desktop.
Save 62mkv/af3ce50d1b3a5246d38b to your computer and use it in GitHub Desktop.
Oneliner to remove remote branches from "origin", that are already merged into "master" (runs in MINGW shell under Windows 10)
git branch -r --merged master | grep -v master | grep -v develop | grep -w "origin" | awk '{print gensub(/origin\//,"","g",$1)}' | xargs git push origin --delete
git remote prune origin
@62mkv
Copy link
Author

62mkv commented Nov 18, 2015

PS: Git Extensions have to be installed (I suppose)

@62mkv
Copy link
Author

62mkv commented Oct 11, 2022

variation:

git log --diff-filter=D --pretty=format:%h -- service/README.md | xargs git branch --list -r --no-contains | awk '{ print gensub(/origin\//,"","g",$1)}' | xargs git push origin --delete

improved version:

git log --diff-filter=D --pretty=format:%h -- service/README.md | awk 'END { if (NR == 1) print }' | xargs -r git branch --list -r --no-contains | awk '{print gensub(/origin\//,"","g",$1)}' | xargs -r git push origin --delete

explainer:

  • git log --diff-filter=D: only show commits where certain path (see further on) is deleted

  • --pretty=format:%h: display just the commit hash per commit

  • -- service/README.md: -- separates revisions from paths, and service/README.md is the path we want to see deleted.

  • awk 'END { if (NR == 1) print }': only outputs the line if input contains exactly one line (otherwise our assumptions about the log were wrong and we just don't do anything)

  • xargs -r git branch --list -r --no-contains: -r aborts if there was no input, otherwise input line is put as the last argument for the command specified after xargs options

  • git branch --list -r --no-contains <commit>: lists remote branches, that do not contain certain commit (in this context, all branches that have diverged from the trunk BEFORE the commit where service/README.md was deleted)

  • awk '{print gensub(/origin\//,"","g",$1)}': replaces origin/ with empty string, making branch names suitable for the last command

  • xargs -r: same as explained above

  • git push origin --delete <branch-name>: deletes remote branch in the "origin" remote

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