Contents

Automatically clean up local once remote branch is deleted

Use this nice PowerShell and Bash one-liner to automatically clean up (delete) your local branch once your remote branch is deleted (merged).

One-liner (PowerShell)

1
git checkout main; git pull; git remote update origin --prune; git branch -vv | Select-String -Pattern ": gone]" | % { $_.toString().Trim().Split(" ")[0]} | % { git branch -D $_ }

That’s how it looks like:

/clean-up-local-and-remote-branches/pwsh.png

Step by step (PowerShell)

1
2
3
4
git checkout main
git pull
git remote update origin --prune
git branch -vv | Select-String -Pattern ": gone]" | % { $_.toString().Trim().Split(" ")[0]} | % { git branch -D $_ }

One-liner (bash)

1
git checkout main && git pull && git remote update origin --prune && git branch -vv | grep ": gone]" | awk "{print \$1}" | xargs -r git branch -D

That’s how it looks like:

/clean-up-local-and-remote-branches/bash.png

Step by step (bash)

1
2
3
4
git checkout main
git pull
git remote update origin --prune
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -D

Update:

Added this little PowerShell snippet with which you can clean up all your local branches that are already merged into main. Faster than doing it manually one by one.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Param(
   [string]$destinationFolder = "."
)

$repos = Get-ChildItem -Path $destinationFolder -Directory

foreach ($repo in $repos) {
  $($repo.FullName)
  Set-Location "$($repo.FullName)"
  git checkout main
  git pull
  git remote update origin --prune
  git branch -vv | Select-String -Pattern ": gone]" | % { $_.toString().Trim().Split(" ")[0]} | % { git branch -D $_ }
}