Things I Learned #24: More Powershell - deleting merged git branches
While I would love to do all my work on my Mac, I end up doing enough in Windows that I sometimes miss the shortcuts I’ve set up on my Mac. They would all work if I ran a bash shell for everything on Windows, but I don’t. I tend to use a Powershell shell on Windows and have it configured to my liking with Oh-My-Posh.
Anyway, when I’ve merged a branch in git, I like to keep my local cleaned up, so I run this:
git branch --merged | egrep -v "(^\*|master|main)" | xargs git branch -d
That will delete all merged branches except for branches named master or main. It’s an easy command to run, and I do have it in an alias.
When I’m on my Windows machine, I miss this, but have never figured out how to do it in Powershell - until today.
What I Learned
The equivalent in Powershell is, as expected, more verbose but it gets the job done.
Get-ChildItem -Path .\ -Include .git -Recurse | ForEach-Object { git branch --merged | Select-String -Pattern "^\*|master|main" -NotMatch | ForEach-Object { git branch -d $_.Line } }
Recurse through the current directory, find git repos, see if any branches have been merged (except master or main), and if so, delete them. Pretty simple. There may be a more efficient way to do it, but it works.
I’ll never be a Powershell guru, but if I’m going to work in Windows, it’s good to know how to do things like this.
Comments