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:

submodule@example:~$ mkdir surface
submodule@example:~$ cd surface
submodule@example:~$ git init
submodule@example:~$ touch destroyer.html
submodule@example:~$ git add .
submodule@example:~$ git commit -m "Add surfae fleet"
submodule@example:~$ mkdir submarines
submodule@example:~$ cd submarines
submodule@example:~$ git init
submodule@example:~$ touch nuclear.html
submodule@example:~$ git add .
submodule@example:~$ git commit -m "Add submarine to fleet"
submodule@example:~$ cd ..
submodule@example:~$ git submodule add ./submarines
submodule@example:~$ git init
submodule@example:~$ git add .
submodule@example:~$ 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. And to delete a Git submodule, follow these steps.

App Architecture
Software Quality
Cloud Computing
Security
SearchAWS
Close