How to create Git submodules in GitHub and GitLab by example
In a previous git submodules tutorial, I added submodules to a stand-alone repository. There was no push or pull to or from GitHub or GitLab. In this GitLab and GitHub submodules add example, I will pull from two independent GitHub repositories and then create the submodule linkage between them. The video at the end of this tutorial demonstrates the same “git submodule add” in GitLab.
The two repositories will be named:
- surface
- submarines

The git submodule add command creates a .gitmodules file.
I will allow you to deduce on your own which one is the parent module and which one is the Git submodule.
How to create submodules in GitHub
The following list of steps will add Git submodule GitHub relationships between two repositories:
- Clone the parent or top-level repository.
- In the root of the parent, issue a “git submodule add” command and provide the GitHub repository’s URL.
- Issue a “git status” command to verify a .gitmodules file is created in the parent project.
- Add the .gitmodules file to the index and perform a git commit.
- Push the GitHub submodule add commit back to the server.
GitHub submodule add commands
The following is the list of commands performed in the GitHub submodule add example.
[email protected]:~$ git clone https://github.com/cameronmcnz/surface.git [email protected]:~$ git log --oneline [email protected]:~$ git cd surface [email protected]:~$ git submodule add https://github.com/cameronmcnz/submarines.git [email protected]:~$ git status [email protected]:~$ git git add . [email protected]:~$ git git commit -m "Add GitHub submodule"
GitHub submodule push
It should be noted that the created GitHub submodules are treated as separate, independent repositories. To prove this point, a file named tugboat.html is added to the surface module and a file named xia.html is added to the added GitHub submodule. Note that a push from each repository is required to move changed files back to the GitHub server. A push from the parent does not automatically force new commits in the submodule to be pushed as well.
[email protected]:~$ git touch tugboat.html [email protected]:~$ git add . [email protected]:~$ git commit -m "Add the tugboat file" [email protected]:~$ git push origin [email protected]:~$ cd submarines [email protected]:~$ touch xia.html [email protected]:~$ git add . [email protected]:~$ git commit -m "Add xia class sub" [email protected]:~$ git push origin