Skip to content

Instantly share code, notes, and snippets.

@mrunkel
Last active April 30, 2019 09:57
Show Gist options
  • Save mrunkel/c0f20127c95ed73f0094dc0879e47a38 to your computer and use it in GitHub Desktop.
Save mrunkel/c0f20127c95ed73f0094dc0879e47a38 to your computer and use it in GitHub Desktop.
Some tricks around managing git branches

delete branches according to a pattern

Use: git branch | grep '<somepattern>'

To select the branches you want to delete. <somepattern> can be a regex or just a text match.

Once you have the list you want, you can use xargs to execute the git command to remove those branches.

Example: Remove all of my branches from the origin:

git branch | grep 'mr/' | xargs git push origin --delete

Then remove all of them except for one locally:

git branch | grep 'mr/' | grep -v 'docker' | xargs git branch -D

grep 'mr/' selects all branches that have mr/ in them. grep -v ignores the branches with docker in them.

But what if you have already removed them locally but forgot to clean origin?

git branch -a | grep 'ko/' | cut -f3- -d/ | xargs -I{} git push origin --delete {}

Should do it. (Assuming the branches have ko/ in them)

What we're doing here is asking git for all branches. Then we grep for the matching pattern. cut allows us to only take portion of the output. The complete output was remotes/origin/ko/something, and since we only want ko/something, we 'cut' the line using / as the field delimiter.

Lastly we use xargs to pass the list to git push origin --delete

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