我有一个Git存储库,其中有几个子模块。如何在git子模块init运行后列出所有子模块的名称?

git子模块foreach命令可以回显子模块的名称,但这只有在它们被签出后才有效,而在init步骤之后没有发生。在签出之前,链中还有更多的步骤需要执行,我不希望将子模块的名称硬连接到脚本中。

那么是否存在一个Git命令来获取所有当前已注册但尚未签出的子模块的名称?


当前回答

为了只返回已注册的子模块的名称,你可以使用这个命令:

grep path .gitmodules | sed 's/.*= //'

可以把它看成是git子模块list,它并不存在。

其他回答

如果你想要显示嵌套的子模块,你可以使用git submodule status或者git submodule status——recursive。

从Git文档中:

显示子模块的状态。的SHA-1 的子模块的当前签出提交 子模块路径和git的输出为SHA-1描述。每一个 如果子模块未初始化,SHA-1将以-作为前缀,+ 如果当前检出的子模块提交不匹配SHA-1 在包含该子模块的存储库的索引中找到U 存在合并冲突。

下面是另一种从. Git modules解析Git子模块名称的方法,不需要sed或花哨的IFS设置。: -)

#!/bin/env bash

function stripStartAndEndQuotes {
  temp="${1%\"}"
  temp="${temp#\"}"
  echo "$temp"
}

function getSubmoduleNames {
  line=$1
  len=${#line} # Get line length
  stripStartAndEndQuotes "${line::len-1}" # Remove last character
}

while read line; do
  getSubmoduleNames "$line"
done < <(cat .gitmodules | grep "\[submodule.*\]" | cut -d ' ' -f 2-)

我注意到在回答这个问题时提供的命令为我提供了我正在寻找的信息:

在.gitmodule中找不到非子模块路径的子模块映射

git ls-files --stage | grep 160000

如果你不介意只对初始化的子模块进行操作,你可以使用git子模块foreach来避免文本解析。

git submodule foreach --quiet 'echo $name'

假设你目前已经注册了,但还没有签出子模块,如下:

$ cat .gitmodules
[submodule ".github/workflows/packages"]
        path = .github/workflows/packages
        url = https://github.com/MarketLeader/Packages
[submodule ".github/workflows/builders"]
        path = .github/workflows/builders
        url = https://github.com/chetabahana/runner
[submodule "docs"]
        path = docs
        url = https://github.com/eq19/lexer

下面是Git命令来获取存储库的根目录:

$ git submodule foreach -q '[[ "$sm_path" == */* ]] || git config remote.origin.url'
https://github.com/eq19/lexer

下面是Git命令在特定路径上获取列表:

$ git submodule foreach -q '[[ ! "$sm_path" == .github/* ]] || git config remote.origin.url'
https://github.com/chetabahana/runner
https://github.com/MarketLeader/Packages

当然,你也可以用其他命令修改git config remote.origin.url。

顺便说一下,我使用的是git 2.38.1版