Article originally published here https://alsohelp.com/blog/git-clean-local-branches
I have some problem with images here on dev.to, so article above may display everything in a better way
Article below :
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.
- Create a new GitHub repository
supercleaner
(tick "create a readme" checkbox) - Clone it locally
git clone git@github.com:_username_/supercleaner.git
cd supercleaner
- 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
- Now go to GitHub https://github.com/_username_/supercleaner/branches
- Delete branches "branch1" and "branch3"
- Good! So now only branch2 and branch4 exist on the remote repository. Locally, you still have 4 branches.
- Go back to the main branch
git checkout main
so that we won't cut the branch on which we are sat :) - 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
- 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!
Top comments (0)