Home > database >  Git submodules checkout to branch if not exist then switch to another
Git submodules checkout to branch if not exist then switch to another

Time:08-01

I would like to have something like:

git submodule foreach --recursive git checkout some_feature_branch || git checkout develop

so if some_feature_branch exists then I want to checkout it otherwise develop. Is it possible to implement that with built-in git or bash commands?

CodePudding user response:

Remember that git submodule foreach passes its argument to a shell, so all you have to do is provide the right shell commands. But if you type a command into a shell (command line interpreter), the shell decides what you meant. The command:

foo some bars || raz a matazz

means, to the shell:

  1. try to foo some bars
  2. if that succeeds, stop; otherwise, try to raz a matazz

That's not what you want here. You want git submodule itself to try to git checkout and if that fails, you want git submodule—not your main shell—to go on to git checkout. That is, you don't want:

  1. for all submodules, try a git checkout
  2. if that succeeds, stop; otherwise try one git checkout

You want:

  1. for all submodules:
    • try a git checkout
    • if that succeeds, go on to the next submodule; if it fails, try another git checkout, and then go on to the next submodule

So that's:

git submodule foreach "git checkout a || git checkout b"

The double quotes here (though single quotes would also work) protect the || so that the top level shell doesn't try to interpret this as:

(git submodule foreach git checkout a) || (git checkout b)

Instead, the top level shell passes the entire "git checkout a || git checkout b" part to the git submodule foreach command. That command—the git submodule foreach—then passes the git checkout a || git checkout b on to one command-line-interpreter run for one submodule. Then git submodule foreach goes on to the next submodule.

(Note that this has very little to do with Git itself: it's basic shell programming. The shell is an interpreter that runs shell programs, and you need to learn to write programs for it.)

  • Related