When we work on different projects and also use the strategy that I always recommend Trunk Based development, it is common that we create many temporary branches. Some of them are removed from the remote repository after doing merge or closing a task, but they remain in our local environment… taking up space and messing up the list of branches. It especially makes it difficult to search for the branches we are working on.
But Git gives us a quick way to clean up those local branches that no longer have their remote equivalent. I’ll explain a command that I use frequently to leave my local repository spotless:
Tabla de contenidos
🧪 The magic command:
git fetch -p && git branch -vv | grep 'gone]' | awk '{print $1}' | xargs git branch -D
🧠 What exactly does it do?
Let’s take it step-by-step:
git fetch -p
- Update remote repository information
- The
-p
(or--prune
) option removes references to remote branches that no longer exist. - ✅ We ensure that Git knows which branches are missing from the remote.
git branch -vv
- Display all local branches with details: tracking, last commit, and if they are out of date.
- This is where Git tells us if a branch is marked as
[gone]
.
grep 'gone]'
- Filter the local branches whose remote tracking has disappeared.
awk '{print $1}'
- Extract only the local branch name from each line
xargs git branch -D
- Forcibly delete all those orphaned local branches
- ⚠️ Use
-D
instead of-d
so you don’t have to check to see if they have been merged.
🎯 When to use this command
- After doing merge of feature branches or fixes.
- After a
git pull
in the main or develop. - When you notice that your list of branches starts to look like a graveyard of old branches.
📌 Extra tip
If you prefer to go easy on yourself, you can change -D
to -d
in the last step:
xargs git branch -d
This will remove only the branches that have already been merged and avoid accidental loss.
With this command, you can keep your environment clean, tidy and free of obsolete branches that just take up space. Try it and see how good a branch cleanup feels