Problem solve Get help with specific problems with your technologies, process and projects.

An example of how to easily add Git submodules

There are several ways a developer can add Git submodules to an existing repository. They can clone from GitLab, they can do a Git submodule add from GitHub or they can manually create all their repositories and submodules.

This tutorial will focus on the latter approach, which will include a Git submodule add example that doesn’t require any integration with GitHub and doesn’t need any pre-existing repositories. It’s a simple, bare bones approach to learn how the Git submodule add command works, and it’s the best way to learn how submodules in Git work.

How to add Git submodules

A developer can follow these eight steps to add Git submodules:

  1. Create a repository with the git init command. This will be the parent module/repository.
  2. Add files and perform at least one commit to the parent repository before you add Git submodules
  3. Add a new subfolder in the Git repository
  4. Perform a git init in the new subfolder
  5. Add files and perform at least one commit on the repository in the subfolder
  6. From the root of the parent module, issue a git submodule add command and specify the path to the subfolder
  7. Perform a git status and verify the parent repository contains a file named .gitmodules
  8. Add the .gitmodules file to the index and then perform a commit.

The git submodule add command create a .gitmodules file.

If a developer completes these steps and doesn’t receive an error message, they will have successfully performed a git submodule add.

Git submodule add commands

The actual commands used in the example are:

submo[email protected]:~$ mkdir surface
[email protected]:~$ cd surface
[email protected]:~$ git init
[email protected]:~$ touch destroyer.html
[email protected]:~$ git add .
[email protected]:~$ git commit -m "Add surfae fleet"
[email protected]:~$ mkdir submarines
[email protected]:~$ cd submarines
[email protected]:~$ git init
[email protected]:~$ touch nuclear.html
[email protected]:~$ git add .
[email protected]:~$ git commit -m "Add submarine to fleet"
[email protected]:~$ cd ..
[email protected]:~$ git submodule add ./submarines
[email protected]:~$ git init
[email protected]:~$ git add .
[email protected]:~$ git commit -m "Add the submodule submarines"

How to add submodules in GitLab

If a developer uses GitLab as their repository of choice, this video demonstrates how to do a Git submodule add with GitLab.

Further git submodule add examples

I performed this Git submodule add example locally by initializing all the required repositories. To see how to add a submodule through a clone, you might want to view this GitHub submodule example.