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

  1. Add a submodule:
git submodule add https://github.com/user/lib.git libs/lib
  1. Clone a repo with submodules:
git clone --recursive https://github.com/user/repo.git
  1. Update submodules:
git submodule update --init --recursive
  1. 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 foreach to 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 --init after cloning.
  • Detached HEAD in submodules is normal; just checkout a branch to make changes.