Git Submodules By Example

Git Submodules By Example

Last updated:
Table of Contents

Create submodule in existing git repo

This registers a submodule under your main repo, but files aren't actually downloaded.

Inside an existing git repository, do:

(this will create a directory called my-other-project in the root directory of the outer repository)

main-repo$ git submodule add git://github.com/some-user/my-other-project.git

Initialize git submodule

Initialize (i.e. populate) a registered git submodule.

This is where files in submodules get actually downloaded.

Example: initialize a submodule called my-other-project.

  1. cd to the submodule directory.

  2. my-other-project$ git submodule init

  3. my-other-project$ git submodule update --remote

Update git submodule

In the submodule directory, do:

my-other-project$ git submodule update --remote

Update all git submodules in repo

In the outer repository, do:

main-repo$ git submodule update --remote

Remove git submodule

This will remove the submodule directory for <submodule_name> and make git forget it ever existed:

  1. main-repo$ git rm --cached <submodule_name>

  2. Delete the relevant lines from file .gitmodules

  3. Delete the relevant section from file .git/config or run main-repo$ git submodule deinit <submodule_name> if on newer git versions

  4. Commit the changes

  5. Delete the now untracked submodule files

  6. Remove directory .git/modules/<submodule_name>

Reset all submodules in git repo

In the outer repository, do:

  1. main-repo$ git submodule foreach --recursive git clean -xfd

  2. main-repo$ git reset --hard

  3. main-repo$ git submodule foreach --recursive git reset --hard

  4. main-repo$ git submodule update --init --recursive

Clone repository with submodules

Example: clone repo repo.git and initialize any submodules within.

$ git clone --recursive git@github.com:name/repo.git

Update repo and submodules together

This is what you need to do if you want to pull both a repository as well as all its submodules:

In the outer repository, do:

  1. main-repo$ git pull origin master

  2. main-repo$ git submodule sync --recursive

  3. main-repo$ git submodule update --init --recursive

Enable submodule information in git status

Update git configuration as follows (in the outer repository):

main-repo$ git config --global status.submoduleSummary true