0

Here is my requirement:

  1. Iterate through all the subfolders of the given directory.
  2. In each subfolder, delete all local branches except master branch.

For item#2, the following statement works when manually executed in a subfolder.

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

I want to create a batch file that will execute the above statement in each subfolder.

I tried the following but could not make it work. Please help me identify what's wrong with the statement.

FOR /D %%G in ("C:\parent\*") Do (echo Updating %%G ...) && (cd %%G) && git branch | grep -v " master" | xargs git branch -D
ariabele
  • 355
  • 1
  • 4
  • 9
  • Remove the parantheses after `do`. Correct syntax is `for %%G in (path) do (command&&command)`. I also suggest using `&` (or better yet, new lines), as `&&` means "do upon success". – Regejok Jun 27 '17 at 01:31
  • @Regejok - Wouldn't it make sense to _not_ run the `git` command if the `cd` failed? – SomethingDark Jun 27 '17 at 01:56
  • @SomethingDark I guess it's the same thing either way, because it's only going to fail if the path contains spaces (in which case you'd need `cd "%%G"`). It would just attempt to delete the branch a second time. – Regejok Jun 27 '17 at 02:11

2 Answers2

0

In each subfolder, delete all local branches except master branch.

That is not how Git works. That might make sense with Subversion, not Git.
Once you have deleted a branch, that branch is gone for the all repo, not for a subfolder.

The only case where you could delete a branch in a Git repo subfolder is if that subfolder is the root folder is a submodule.

Plus, you might consider using -d instead of -D, to avoid deleting branches not fully merged. See "Can I delete all the local branches except the current one?".

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
0

thank you for all the help.

It turns out that I am encountering the following error:

'grep' is not recognized as an internal or extenal command.

I did not see it because I execute the batch file by double clicking it, then command prompt will display and immediately close so I missed the error message.

Anyway, the batch file with the contents above worked as expected when I execute it using Git bash.

Note that this is only for maintenance purposes, assuming that I only need the master branch and all local branches are merged.

ariabele
  • 355
  • 1
  • 4
  • 9