Let’s understand Git Submodule

What is git submodule?

It is another git project inside your git repository. If you working on multiple git projects but need them in one repository instead. You will be happy to setup git submodule.

So here I have two git repositories for example:


And since I’m updating the repo-b frequently, I want my repo-b to be inside the repo-a so it helps me to work with multiple repos as possible and easy to maintain codes across the repo and be able to work more faster and efficiently.

Setup git submodule

Add git submodule in your current repo

$ git clone git@github.com:muffat/repo-a.git
$ cd repo-a/
/repo-a$ git submodule add git@github.com:muffat/repo-b.git

Commit and push your submodule

/repo-a$ git add .
/repo-a$ git commit -m "Add submodule repo-b"
/repo-a$ git push origin master

Note that, git submodule doesn’t automatically get pulled after you clone your repository (repo-a). You need to do manual initialize and pull your submodule. So after you clone your repository, you will find out that your submodule directory (repo-b) is empty.

$ git clone git@github.com:muffat/repo-a.git
$ cd repo-a/
/repo-a$ cd repo-b/
/repo-a/repo-b/$ ls

go to submodule directory, and do this:

/repo-a$ cd repo-b/
/repo-a/repo-b/$ git submodule init
/repo-a/repo-b/$ git submodule update

How to git clone including submodules

$ git clone --recursive git@github.com:muffat/repo-a.git

Some problem occurred whenever I tried to clone with recursive. It failed to fetch the submodule repository because of the permission. Although my submodule is a public repository, yet still failed.

Then I changed the url of submodule from git to be https.

$ cat .gitmodules
[submodule "repo-b"]
path = repo-b
url = https://github.com/muffat/repo-b.git
branch = master

After that, the git recursive cloning was working.

Leave a Reply

Your email address will not be published. Required fields are marked *