Last Updated: May 1, 2025
Adding & Cloning Submodules
git submodule add url pathAdd a submodule at the specified path
git clone --recurse-submodules urlClone repo AND all submodules in one command
git clone urlClone normally (submodule dirs will be empty)
git submodule initInitialize submodule config after a normal clone
git submodule updateFetch and checkout the committed submodule SHA
git submodule update --init --recursiveInit, update, and recurse into nested submodules
git submodule statusShow current SHA of each submodule
Updating Submodules
cd subdir && git pull origin mainUpdate submodule to latest remote (manual)
git submodule update --remoteUpdate all submodules to their remote HEAD
git submodule update --remote --mergeUpdate and merge remote changes
git submodule foreach git pull origin mainRun git pull in every submodule
git submodule update --recursiveUpdate submodules and their nested submodules
git diff --submoduleShow submodule SHA changes in diffs
Removing Submodules
git submodule deinit pathRemove submodule from .git/config
git rm pathRemove submodule from the index and working tree
rm -rf .git/modules/pathDelete the submodule's Git data (manual cleanup)
git rm --cached pathUnregister submodule without deleting files
git commit -m Remove submoduleCommit the submodule removal
Pitfalls & Best Practices
| Item | Description |
|---|---|
Detached HEAD | Submodules always check out a specific commit, not a branch |
Branch Tracking | Set branch = main in .gitmodules for easier updates |
Circular Dependencies | Avoid submodules that reference each other |
Monorepo Alternative | Consider git subtree or monorepo tools for simpler workflows |
CI Configuration | Always use --recurse-submodules in CI clone steps |
.gitmodules File | Tracked config file — commit changes to share with team |
Fork & Replace | If you need to modify a submodule, fork it first |
Shallow Submodules | git submodule update --depth 1 for faster CI clones |
Pro Tip: Always commit the submodule pointer change separately from your own code changes — it makes reviewing and reverting much easier.