← Back to Git Course | Chapter 6: Advanced Commands | Lesson 1 of 7

Git Submodules

Adding a Submodule

A submodule embeds another Git repository as a subdirectory of your project, pinned to one specific commit rather than tracking a branch. This is the standard way to depend on a separate shared library's exact history without merging its commits into your own repository.

Example: Adding a Submodule

bash
git submodule add https://github.com/user/library.git libs/library

Cloning Repositories with Submodules

When you git clone a project containing submodules, Git creates the submodule directories but leaves them empty — the parent repo only stores a pointer to which commit each submodule should be at. You must run git submodule init and git submodule update (or clone with --recurse-submodules) to actually populate them.

Example: Cloning Repositories with Submodules

bash
git clone --recurse-submodules https://github.com/user/repo.git
git submodule update --init --recursive

Updating Submodule Code

git submodule update --remote fetches the latest commits from each submodule's own remote and moves your local checkout forward to match, but it does NOT automatically update the parent repository's pinned pointer — you still need to git add and commit that pointer change yourself.

Example: Updating Submodule Code

bash
git submodule update --remote
git add libs/library
git commit -m "Update submodule"

Running Submodule Commands

git submodule foreach '<command>' runs an arbitrary shell command inside every registered submodule directory in sequence, saving you from manually cd-ing into each one — useful for something like running git status across all of them at once.

Example: Running Submodule Commands

bash
git submodule foreach 'git status'

Deleting a Submodule

Removing a submodule cleanly takes more than deleting its folder: you need to remove its entry from .gitmodules and .git/config, then run git rm --cached <path> to untrack it, and finally delete the leftover .git/modules/<path> cache directory — skipping any of these steps leaves stale references behind.

Example: Deleting a Submodule

bash
git rm --cached libs/library
rm -rf .git/modules/libs/library
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.