2

When working on projects with Git Flow or similar workflow where more than one stable branch exists I create a lot of feature branches (feature/do-something-1, hotfix/fix-bug-1, etc.).

Sometimes I need to clear the list of local branches because it is literally impossible to manage them with dozens of rudimentary branches. I usually delete them one at a time by copying and pasting the branch names into the git branch -d command. But it takes so long that it's easier to delete the entire repository and clone again.

I want to delete all of them except master and develop in one command (without writing additional shell script/aliases), but all solutions I've found on the internet only allow you to delete everything except one branch (master, for example). This is not an appropriate solution. Has anyone faced a similar problem?

AndreyProgr
  • 537
  • 4
  • 14
  • 1
    Why could you not adjust what you have found for deleting all but one branch to deleting all but two branches? – mkrieger1 Nov 25 '21 at 20:51

2 Answers2

10

Let's do it in steps so we can break down the command and understand what it does:

 git branch | grep -v " master$" | grep -v " develop$" | xargs git branch -D

Note: You cannot delete a branch that is currently checked out.

Step by step:

zrrbite@ZRRBITE MINGW64 /d/dev/branch_del_test (master)
$ git branch
  develop
* master
  test
  test2

zrrbite@ZRRBITE MINGW64 /d/dev/branch_del_test (master)
$ git branch | grep -v " master$"
  develop
  test
  test2

zrrbite@ZRRBITE MINGW64 /d/dev/branch_del_test (master)
$ git branch | grep -v " master$" | grep -v " develop$"
  test
  test2

zrrbite@ZRRBITE MINGW64 /d/dev/branch_del_test (master)
$ git branch | grep -v " master$" | grep -v " develop$" | xargs git branch -D
Deleted branch test2 (was 7767978). <-- only the output of the last xargs run is shown

zrrbite@ZRRBITE MINGW64 /d/dev/branch_del_test (master)
$ git branch
  develop
* master
zrrbite
  • 1,180
  • 10
  • 22
  • Very nice answer. Can you please briefly explain the command in the answer? it will be helpful if we want to modify this command for other uses. Thanks. – Shyam Joshi Nov 26 '21 at 03:23
  • 1
    I've updated the answer with a step-by-step walk through of the command. – zrrbite Nov 28 '21 at 09:24
4

Here is a simpler variant of same answer:

git branch -D $(git branch | grep -v -e "master$" -e "develop$")
Dudi Boy
  • 4,551
  • 1
  • 15
  • 30