Skip to content

Instantly share code, notes, and snippets.

@iamandrewluca
Last active November 4, 2021 09:18
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamandrewluca/e184f30a3013857bf3032b70fd4b0aa9 to your computer and use it in GitHub Desktop.
Save iamandrewluca/e184f30a3013857bf3032b70fd4b0aa9 to your computer and use it in GitHub Desktop.
Git alias to remove all local branches that are gone on remote

Create alias manually in ~/.gitconfig file (recommened):

[alias]
	gone = "!f() { git fetch --all --prune; git branch -vv | awk '/: gone]/{print $1}' | xargs git branch -D; }; f"

Create alias (problematic):

git config --global alias.gone '!f() { git fetch --all --prune; git branch -vv | awk "/: gone]/{print $1}" | xargs git branch -D; }; f'

Usage:

git gone

Blog post:

https://dev.to/iamandrewluca/remove-gone-git-branches-36eh

@djhoese
Copy link

djhoese commented Nov 4, 2021

This command doesn't always work as expected. For me the double quotes used on the awk command result in it printing the entire line from git branch. The solution is to swap the single/double quote usage and escape the variable expansion:

git config --global alias.gone "!f() { git fetch --all --prune; git branch -vv | awk '/: gone]/{print \$1}' | xargs git branch -D; }; f"

This was very obvious when I had a branch most recent commit that had "-P" in the commit message. This was being interpreted by git branch -D and raised an error.

@iamandrewluca
Copy link
Author

Yes, creating this alias from command line is a little bit problematic because involves a lot of quotes 🙂

Easier would be to open ~/.gitconfig file in a text editor and add it manually

[alias]
	gone = "!f() { git fetch --all --prune; git branch -vv | awk '/: gone]/{print $1}' | xargs git branch -D; }; f"

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