Friday, October 5, 2018

git: batch script to clean/delete(or list) your local branches that are merged/removed(deleted) from remote / server



How to list/delete/clean all the local branches (usually after PR merge) that you have on local but was deleted from remote/server (with simple batch/command line script on windows)?

Quick Answer:
Below is what i use as soon as i squash merge the pull request in single execution (to checkout to master, fetch prune, delete the local branches that are in my local but deleted in source and the do a git pull)

Command line:
git checkout master && git fetch --prune && git branch -vv | for /f "tokens=1" %a in ('findstr /R /C:": gone]"') do (git branch -D %a) && git pull
If you are creating a batch file (say cleanupAfterPRMerge.bat), put below inside:
git checkout master && git fetch --prune && git branch -vv | for /f "tokens=1" %%a in ('findstr /R /C:": gone]"') do (git branch -D %%a) && git pull

Step by step:
run "git checkout master"
run "git fetch --prune"
  • On windows command prompt:
    • details of those branches: 
      • git branch -vv | findstr /R /C:": gone]"

    • if you don't want the details and just the branch names, use
      • git branch -vv | for /f "tokens=1" %a in ('findstr /R /C:": gone]"') do echo %a

    • if you are happy with it and would delete all those local branches that are deleted from remote
      • git branch -vv | for /f "tokens=1" %a in ('findstr /R /C:": gone]"') do git branch -D %a



if you want to delete one by one or specific local branch:
  • if its still in remote branch and merged 
    • git branch -d [Branch name]
  • if its its not merged or deleted from remote/server or local only
    • git branch -D [Branch name]
[posting this as i didn't find a quick answer on the web for windows commandline/batch (with out installing additional software)]

Hope this helps someone.


-- Tony Julien





No comments: