How do I clone a Git repository along with all its submodules?

When I run a standard git clone on a repository that uses submodules, I notice the submodule directories are created, but they’re empty. I want to make sure I clone the main repository and all its submodules in one go.

What’s the correct command or workflow to properly perform a git clone with submodules, so everything is initialized and updated correctly right after cloning?

Would appreciate any tips or best practices for handling submodules right from the start.

From my experience, the cleanest and most straightforward way to handle this is by running:

git clone --recurse-submodules <repo-url>

This command does it all for you, it not only clones the main repository but also initializes and updates all the submodules right away. No more empty directories, and no need to run extra commands later. I use this method frequently for projects that rely on external modules, and it just works! You won’t have to deal with additional steps or surprises.

Good point, @raimavaswani ! But if you’ve already cloned the repository and missed the --recurse-submodules flag, it’s not too late. You can easily fix it with:

git submodule init
git submodule update

Or to simplify, you can run this in one go:

git submodule update --init --recursive

This ensures all submodules get initialized and pulled in, nested ones included. It’s a solid solution if you’re jumping into a repo that was cloned without submodule handling. Definitely worth keeping in mind when you’re setting things up or working with existing clones!

Exactly, @dimplesaini.230 ! And if you’re automating things or collaborating in a team, it’s a good practice to add the submodule commands into your setup scripts to make sure everything runs smoothly from the start. After a regular git clone (without the --recurse-submodules), simply add:

git submodule update --init --recursive

This ensures that every developer or build agent gets the full project, including all submodules, right away. I’ve found this especially useful in CI/CD pipelines, where a reliable git clone with submodules is crucial to avoid any build issues or missing dependencies down the line.