As I was working on my Vue and Supabase Boilerplate project, I completed many features. I needed to have a script that would remove any local branch not named main or develop or that wasn’t the checked-out branch or that didn’t have a remote equivalent.
Yes, what follows will remove any branch that you may have created and not yet pushed ⚠️. So be careful.
Let’s see how to speed up the clean-up process.
The Bash Script
I love bash scripts to do small tasks like this. With it, you can achieve so much without any new software or service. Using Git Bash, which comes with Git by default, you can run the following:
|
|
A Little Caveat With Former Remote Branches
If you run the script and you have had remote branches deleted, after a PR completion, for example, you may notice that some branches are flagged: “Remote branch exists for a-branch” but they really don’t exist anymore.
What’s going on?
How Remote References Work
Remote-tracking branches are local references that represent the state of branches in your remote repository. They act as bookmarks to remember where the remote branches were during your last synchronization (see Git documentation).
When someone deletes a branch on the remote server, your local repository won’t automatically remove its reference to that branch until you explicitly prune it (read more about branch pruning).
These remote-tracking references are stored locally in your .git/refs/remotes/ directory (or in the .git/packed-refs file for optimized storage), while your remote configuration settings are kept in .git/config. They’re managed separately from the actual remote repository state.
This separation is why you need to explicitly tell Git to clean up these references when they become stale.
Updating Remote References
There are several ways to update these stale references:
- Using
git fetch with prune
|
|
This command fetches updates from the remote repository and removes any remote-tracking references that no longer exist on the remote.
- Using
git remote prune
|
|
This command specifically removes stale remote-tracking branches without fetching new updates.
- Enable Automatic Pruning
To automatically prune stale references whenever you fetch or pull, you can configure Git with:
|
|
This setting ensures your remote branch references stay clean without manual intervention.
Conclusion
All you have to do now is to create a file clean-git-local-branches.sh and run it.
|
|
Then, once you’re satisfied with the dry run, run the script with -D to effectively delete the local branches.
Follow me
Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.
Photo by Francesco Ungaro.