git submodule
Include other repositories inside your repository
The 'git submodule' command embeds another Git repository in a folder of yours, pinned to one exact commit. Your repository records only which commit of the submodule to use; the submodule keeps its own history. It is how projects include shared libraries they do not want to copy. Cloning needs --recurse-submodules (or git submodule update --init) to fetch them.
Synopsis
git submodule add <url> [<path>]
git submodule update --init --recursive
git submodule status
git submodule foreach <command>Examples
Add a library
git submodule add https://github.com/acme/ui.git lib/uiClones it and records its commit.
After cloning
git submodule update --init --recursiveFetch every submodule.
Clone with them
git clone --recurse-submodules <url>All in one step.
Update to latest
git submodule update --remoteMove each submodule to its branch’s latest commit.
Workflow Examples
cd lib/ui && git pullMove the submodule forward
cd ../.. && git add lib/uiRecord the new commit
git commit -m "Update ui library"Commit it
Troubleshooting
Empty submodule folder
Cause: Submodules were not fetched
git submodule update --init --recursive
Tips & Pitfalls
Best Practices
- ✓Set git config --global submodule.recurse true so pull and checkout update submodules.
Common Mistakes
- ✗Cloning without --recurse-submodules and getting empty folders.
- ✗Committing inside a submodule on a detached HEAD and losing the work.
- ✗Forgetting to commit the new submodule commit in the parent repository.
FAQ
Only the submodule’s URL (in .gitmodules) and the exact commit it uses.