Updating Submodules
One common task when working with submodules is keeping them up-to-date with their remote repositories. Let's learn how to update our submodule.
Initializing and Updating Submodules
If you've just cloned a repository that contains submodules, you'll need to initialize and update them. For our existing repository, we can demonstrate this process with:
cd ~/project/main-repo
git submodule init
git submodule update
The init
command initializes your submodules configuration, and the update
command fetches the data and checks out the commit specified in your main repository.
You can also combine these commands:
git submodule update --init
Updating Submodules to Latest Remote Version
If you want to update a submodule to the latest commit in its remote repository, you can use:
cd ~/project/main-repo
git submodule update --remote libs/libgit2-backends
This command fetches the latest changes from the remote repository and updates the submodule. You should see output indicating that Git is fetching changes.
After running this command, let's check the status of the submodule:
git submodule status
You'll notice the output now shows a plus sign (+
) at the beginning, indicating that the submodule's checked-out commit differs from what is recorded in the main repository:
+abcdef1234567890abcdef1234567890abcdef12 libs/libgit2-backends (origin/HEAD)
To confirm the changes to your main repository, run:
git status
You should see output indicating that the submodule has been modified:
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: libs/libgit2-backends (new commits)
Committing the Updated Submodule Reference
To record the updated submodule state in your main repository, you need to add and commit the changes:
git add libs/libgit2-backends
git commit -m "Update libgit2-backends submodule to latest version"
The output should indicate that you've successfully committed the new submodule reference.
Checking the Updated Status
After committing the updated submodule reference, let's check the status again:
git submodule status
The output should no longer have a plus sign at the beginning, indicating that the submodule is now in sync with what is recorded in the main repository:
abcdef1234567890abcdef1234567890abcdef12 libs/libgit2-backends (origin/HEAD)
Understanding Submodule Update Options
The git submodule update
command has several options that control how updates are performed:
--remote
: Update to the latest commit on the remote tracking branch
--merge
: Merge changes if the current branch is behind the remote
--rebase
: Rebase changes if the current branch is behind the remote
--recursive
: Update nested submodules too
For most basic use cases, git submodule update --remote
is sufficient.