Introduction
Using the git clone
command to obtain a local copy of a remote repository is a standard procedure when working in Git. However, if the cloned repository contains submodules, Git does not clone the contents of the submodule directories automatically. Instead, they remain empty, pending initialization and update.
This article explains how to clone a repository that contains submodules and how to ensure the submodule content is accessible.
Prerequisites
- Git installed.
- Access to a remote Git repository with submodules.
git submodule update Command
git submodule update is usually the only command a user needs to obtain the submodule content of the cloned repository. The steps below describe the short procedure for using the command.
1. Clone the repository you need by providing its URL to the git clone
command:
git clone [repository-url]
The output shows the progress of the operation.
2. Go to the directory containing the cloned repository:
cd [repository-directory]
3. Use the following git submodule update
command to populate the submodule directories:
git submodule update --init --recursive
The --init
flag eliminates the need to run the git submodule init command before updating. The --recursive
option ensures that Git updates all the submodules, including those nested within other submodules.
When the process completes, all the submodules are initialized and checked out.
git clone Command
Newer versions of Git have several features designed to simplify and speed up the submodule checkout process. With Git version 1.9 and later, you can initialize and update the repository's submodules by adding the --recurse-submodules
option to the git clone
command.
Use the following syntax:
git clone --recurse-submodules [repository-url]
The output consists of three parts in which Git:
- Clones the repository found at the given URL.
- Initializes all the submodules it finds.
- Updates the content of the submodule directories.
Note: If you run a Git version between 1.6.5 and 1.9, you can still perform submodule checkout with git clone
. However, use the --recursive
flag instead of --recurse-submodules
:
git clone --recursive [repository-url]
The newer versions of Git (2.8 and later) allow you to optimize the submodule checkout process by adding the -j8
flag. This flag tells Git to fetch up to 8 submodules at the same time, which shortens the checkout procedure.
To include the flag, use the syntax below:
git clone --recurse-submodules -j8 [repository-url]
Conclusion
The purpose of this guide was to introduce you to the methods for cloning Git repositories with submodules. Learn more about submodules by reading our Git Submodule Guide.
If you are a Git beginner, read How to Use Git for an overview of its basic features.