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:
- Create a repository with the git init command. This will be the parent module/repository.
- Add files and perform at least one commit to the parent repository before you add Git submodules
- Add a new subfolder in the Git repository
- Perform a git init in the new subfolder
- Add files and perform at least one commit on the repository in the subfolder
- From the root of the parent module, issue a git submodule add command and specify the path to the subfolder
- Perform a git status and verify the parent repository contains a file named .gitmodules
- 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.
Cameron McKenzie is an AWS Certified AI Practitioner, Machine Learning Engineer, Solutions Architect and author of many popular books in the software development and Cloud Computing space. His growing YouTube channel training devs in Java, Spring, AI and ML has well over 30,000 subscribers.