How to work with Git submodules
· Category: Git
Short answer
Git submodules let you keep a Git repository as a subdirectory of another Git repository.
Steps
- Add a submodule:
git submodule add https://github.com/user/lib.git libs/lib
- Clone a repo with submodules:
git clone --recursive https://github.com/user/repo.git
- Update submodules:
git submodule update --init --recursive
- Pull upstream changes in a submodule:
cd libs/lib
git pull origin main
Tips
- Submodules are pinned to a specific commit, not a branch.
- Use
git submodule foreachto run commands across all submodules. - Consider alternatives like package managers or monorepo tools if submodules feel cumbersome.
Common issues
- Empty submodule folders: run
git submodule update --initafter cloning. - Detached HEAD in submodules is normal; just checkout a branch to make changes.