What I want to achieve is whenever I use git checkout on my main repository for example:
git checkout my-branch
my submodules will follow my-branch instead of a detached head.
Is it possible, and if yes, how?
If those submodule repositories have a my-branch of their own, they can be 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
But that involves repeating that each time you checkout a branch in the parent repo.
torek points out in the comments that those submodules might have submodules of their own, hence the need for the --recursive
option.
You might also want to add
--recursive
and/or--no-fetch
to yourgit submodule update --remote
command.
Rather than individualgit config -f
operations, you might wantgit submodule foreach
, again maybe with--recursive
.
git submodule foreach -q --recursive 'git config -f $toplevel/.gitmodules submodule.$name.branch my_branch'
In multiple lines for readability:
git submodule foreach -q --recursive \
'git config -f $toplevel/.gitmodules submodule.$name.branch my_branch'
Then you can checkout each submodule to that branch:
git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; git checkout $branch'
In multiple lines for readability:
git submodule foreach -q --recursive \
'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; \
git checkout $branch'