是否可以与子模块同步检出主存储库的分支?

Is it possible to checkout branches of main repository in sync with submodules?

我想要实现的是每当我在我的主存储库上使用 git checkout 例如:

git checkout my-branch

我的子模块将跟随我的分支而不是分离的头。

是否可能,如果可能,如何实现?

如果那些子模块存储库有自己的 my-branch,它们可以是 declared to follow that branch

cd /path/to/your/parent/repo/Foo
git config -f .gitmodules submodule.bar1.branch my-branch
git config -f .gitmodules submodule.bar2.branch my-branch

git submodule update --remote

但这涉及到每次您在父存储库中签出分支时重复这一点。

torek points out 这些子模块可能有自己的子模块,因此需要 --recursive 选项。

You might also want to add --recursive and/or --no-fetch to your git submodule update --remote command.
Rather than individual git config -f operations, you might want git submodule foreach, again maybe with --recursive.

git submodule foreach -q --recursive 'git config -f $toplevel/.gitmodules submodule.$name.branch my_branch'

多行以方便阅读:

git submodule foreach -q --recursive \
  'git config -f $toplevel/.gitmodules submodule.$name.branch my_branch'

然后您可以将每个子模块检出到该分支:

git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; git checkout $branch'

多行以方便阅读:

git submodule foreach -q --recursive \
  'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; \
   git checkout $branch'