windowsbashgitforeachgit-submodules

How to run multiple commands within git submodule foreach?


What I have tried

git submodule foreach git checkout main
git submodule foreach git add --all
git submodule foreach git diff-index --quiet HEAD || git commit -m "%CommitMessage%"
git submodule foreach git push

This runs command 1 for all submodules, then command 2 for all submodules, etc.

What I would like

I would like to only have one foreach, and do all of the commands for a submodule at once, then move on to the next submodule.

Question

Is there a way to have the git submodule foreach call a method, or in some way call multiple commands at once?

I want to do this within a batch script on Windows.


Solution

  • To complement larsks' helpful Unix solution (which would also work in Unix-like environments on Windows, such as Git Bash and WSL) with a solution for Windows, from a batch file (see the next section for PowerShell):

    git submodule foreach "git checkout main && git add --all && git diff-index --quiet HEAD || git commit -m \"%CommitMessage%\" && git push"
    

    The PowerShell perspective (on both Windows and Unix-like platforms):

    # NOTE: In Windows PowerShell and PowerShell (Core) 7.2-,
    #       you must manually \-escape the embedded " chars.
    #       (... -m \"$CommitMessage\")
    #       $CommitMessage is expanded *by PowerShell*, up front.
    git submodule foreach @"
      git checkout main && 
      git add --all && 
      git diff-index --quiet HEAD || git commit -m "$CommitMessage" && 
      git push
    "@
    

    Important: