Let's say your local branches are messy. Here is a quick guide about how to clean 'em up.

· git  · 2 min read

Git clean local branches

Let's say your local branches are messy. Here is a quick guide about how to clean 'em up.

The problem

Let’s say you are on your machine, and your local repository has too many branches :

my_lovely_but_old_project> git branch
* Story-4965-password-complexity
  Story-4998-Clean-up-code-from-unnecesssary-comments
  PM25-modification
  blabla
  debug1
  debug2
  debug3
  debug4
  blabla2
  debugging-lm-4730
  doc-get-incident
  doc-incident
  docs/v5apiLocations
  document-api-separately
  main
  development
  refactor/gcalendar-sync
  .
  .
  .
  (... and much more branches)

You want to locally clean branches that are already destroyed on the remote repository

The solution

There you go:

git fetch -ap --progress 2>&1 | grep -E '\[deleted\]' | awk '{print $NF}' | sed 's|origin/||'  | xargs git branch -D
  • p option of fetch will prune remotes that don’t exist anymore
  • progress option scratched my head… without it, the terminal is unable to read the output of the git command
  • awk print NF... reads the last word
  • sed ... removes un-needed origin prefix (we delete local branches)
  • xargs git branch -D finally removes all required branches
  • pfew!

Recreate the problem at home

Replace username by your actual GitHub user name.

  1. Create a new GitHub repository supercleaner (tick “create a readme” checkbox)
  2. Clone it locally git clone git@github.com:_username_/supercleaner.git
  3. cd supercleaner
  4. Create 4 branches locally
git checkout -b branch1 && git push origin branch1
git checkout -b branch2 && git push origin branch2
git checkout -b branch3 && git push origin branch3
git checkout -b branch4 && git push origin branch4
  1. Now go to GitHub https://github.com/_username_/supercleaner/branches
  2. Delete branches “branch1” and “branch3”
  3. Good! So now only branch2 and branch4 exist on the remote repository. Locally, you still have 4 branches.
  4. Go back to the main branch git checkout main so that we won’t cut the branch on which we are sat :)
  5. Kboom: it’s time to try the command:
git fetch -ap --progress 2>&1 | grep -E '\[deleted\]' | awk '{print $NF}' | sed 's|origin/||'  | xargs git branch -D
  1. List all what you have locally. Did it worked?
git branch

Summary

By tweaking well-documented git command, we can remove pain that we usually don’t take time to address.

I hope you enjoyed it!

Share:
Back to Blog

Related Posts

View All Posts »