Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all merged local branches in Git with PowerShell

Tags:

git

powershell

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.

like image 970
s.harris Avatar asked Jul 04 '18 10:07

s.harris


People also ask

How do I delete multiple local branches in git?

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.

Can you delete branches after merge?

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).


1 Answers

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!

like image 160
s.harris Avatar answered Sep 20 '22 16:09

s.harris