Git Submodule

A submodule is a Git repository inside another Git repository. It lets you use the code of another project (like a shared library) in your own project, and still keep the two histories separate. The main project only remembers which commit of the submodule it uses.

Syntax

git submodule add <url> <path>
git submodule update --init --recursive
git submodule update --remote
git submodule status

Add a submodule

We make a small library repository, and then add it into a project.

Terminal output

$ git submodule add ../lib libs/math
Cloning into '/home/robin/work/app/libs/math'…
done.
$ git status -s
A .gitmodules
A libs/math

Git made a new file .gitmodules which keeps the URL and path of the submodule. The folder libs/math is saved as a link to a single commit of the library.

Terminal output

$ cat .gitmodules
[submodule "libs/math"]
path = libs/math
url = ../lib
$ git commit -q -m "Add math library as submodule"
$ git submodule status
c8f03526d65d9eac3dc098bda646353d4ca2ee2c libs/math (heads/main)

Clone a project that has submodules

A normal clone creates the submodule folder, but it is empty. You need to download its content:

git clone --recurse-submodules <url>
git submodule update --init --recursive

Update a submodule

To take the latest commit of the submodule’s remote branch:

git submodule update --remote libs/math
git add libs/math
git commit -m "Update math library"

Remove a submodule

Removing a submodule needs a few steps, because the data is in three places (the working folder, .gitmodules and .git/modules).

Terminal output

$ git submodule deinit -f libs/math
Cleared directory 'libs/math'
Submodule 'libs/math' (../lib) unregistered for path 'libs/math'
$ git rm -f libs/math
rm 'libs/math'
$ rm -rf .git/modules/libs/math
$ git commit -q -m "Remove math submodule"
$ git status -s
$ ls
app.txt
libs

The steps in order: de-register the submodule, remove it with git rm (this also updates .gitmodules), delete its hidden data, and commit.

When to use submodules

  • A shared library used in many projects.
  • A theme or plugin which has its own repository.
  • A big component that other teams maintain.

Submodules can be confusing for beginners, because people forget to update or push them. Package managers like Composer, npm or pip are often easier for code libraries. Also see the related code example: Git submodule remove.

Note: After you change something inside a submodule, commit and push it first in the submodule, and then commit the new pointer in the main project. Next: Git Hooks.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.