Search code examples
gitgit-branchgit-submodules

How to clone a git repository with its submodules checkout on their default branches?


On the question:

  1. How to correctly call a git submodule symlinked?

Was figured it out it is necessary to checkout the git submodules to their default branch when a git clone --recursive is performed, but how to do that?

I tried searching and found this other question:

  1. Easy way pull latest of all submodules

Suggesting to use the command git clone --recurse-submodules but after cloning the repository its submodule still not checkout on their default branches.


Solution

  • You can use git submodule foreach to run an arbitrary command in each submodule. The --recursive flag will recurse through the submodules' submodules. git remote show [name-of-remote] will say which branch [name-of-remote] currently has active. Combining them with a few other tools to clean up git remote show's output gives:

    git submodule foreach --recursive "git checkout $(git remote show origin | grep 'HEAD branch' | sed 's/.*: //')"
    

    This is, of course, dependent on already having cloned the submodules.