使用“git submodule foreach”命令在非零退出后继续循环子模块

70

我有一个包含多个子模块的项目。我想使用以下命令循环遍历每个子模块:

git submodule foreach npm install

即使其中一个子模块返回错误(非零返回代码),我也希望脚本继续循环遍历每个子模块。目前,任何一个子模块运行此命令时返回非零返回代码都会导致git停止循环遍历其余的子模块。

有什么建议可以实现这一点吗?


git submodule foreach 'yarn' - danday74
3个回答

139

只需让您的命令始终返回0代码,如下所示:

git submodule foreach 'npm install || :'

这是从手册中摘录的:git help submodule

   foreach
       Evaluates an arbitrary shell command in each checked out submodule.
       The command has access to the variables $name, $path, $sha1 and
       $toplevel: $name is the name of the relevant submodule section in
       .gitmodules, $path is the name of the submodule directory relative
       to the superproject, $sha1 is the commit as recorded in the
       superproject, and $toplevel is the absolute path to the top-level
       of the superproject. Any submodules defined in the superproject but
       not checked out are ignored by this command. Unless given --quiet,
       foreach prints the name of each submodule before evaluating the
       command. If --recursive is given, submodules are traversed
       recursively (i.e. the given shell command is evaluated in nested
       submodules as well). A non-zero return from the command in any
       submodule causes the processing to terminate. This can be
       overridden by adding || : to the end of the command.

       As an example, git submodule foreach 'echo $path `git rev-parse
       HEAD`' will show the path and currently checked out commit for each
       submodule.

bash中,help :命令的用法为::

:: :
    Null command.

    No effect; the command does nothing.

    Exit Status:
    Always succeeds.

永远成功 :)


11
git submodule foreach 'npm install || true'会执行相同的操作。 - Maksim Dmitriev
1
它在Windows上无法工作。本来应该可以的吧?即使使用bash,'<command>'也只尝试执行第一个命令,但还是会出错。 - Idemax
2
尝试使用git bash。@MarceloFilho - MaBe
@MarceloFilho:请开一个新问题,描述这个问题(以便每个人都可以重现),并链接到这个问题。 - gniourf_gniourf
在 Mac 上使用双引号 " 而不是单引号 '。 - ort11
显示剩余2条评论

5
在Windows批处理中,您可以通过添加一个和另一个不执行任何操作的命令来设置返回代码为0:
git submodule foreach "npm install & echo done"

编辑:原本的答案使用分号来实现,这是不正确的。


是的,这就是Git文档完全忽略的部分:非POSIX shell。+1 - 0xC0000022L

2

请不要使用 shell 解析 .gitmodules ... 有一种方法可以做到这一点,那就是:git config --file .gitmodules --get-regexp <regexp> ... 然后可以将其导入 while 中。 - 0xC0000022L
2
@0xC0000022L 这个回答已经有10年了 ;) (因为我已经非常习惯使用git了) ... - Idriss Neumann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接