How can I iterate through my branches, filter out merged branches and delete them using Git for Windows in Powershell?
I have already attempted some research, but every answer I have found revolves around using bash specific commands, such as grep and xargs. Powershell does not have the same commands so these do not work for me.
However, from that research I have found that git for-each-ref --format '%(refname:short)' refs/heads
can show me all local branches, while git branch -d
will delete any merged branch. However, piping these two commands together (git for-each-ref --format '%(refname:short)' refs/heads | git branch -d
) does not work as the output from the first command is not piped as I expected.
You can use git gui to delete multiple branches at once. From Command Prompt/Bash -> git gui -> Remote -> Delete branch ... -> select remote branches you want to remove -> Delete.
There's no problem in deleting branches that have been merged in. All the commits are still available in the history, and even in the GitHub interface, they will still show up (see, e.g., this PR which refers to a fork that I've deleted after the PR got accepted).
After some playing about, and further research into Powershell commands, I have found a solution!
While Powershell does not have an xargs
command, it does have something similar called ForEach-Object
. This command allows us to work on each line of the output from git for-each-ref
. For this specific problem, the following line did the trick:
git for-each-ref --format '%(refname:short)' refs/heads | ForEach-Object {git branch $_ -d}
The curly braces after the ForEach-Object
command contains the command you wish to run, while the $_
variable stands for each line of output from the piped command.
Hope this helps other newbie Powershell/Git users out there!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With