Useful Git Submodule Commands

Posted on In Linux

git submodule is a very useful tools in git to include other git repositories in one repository to handle cases such as library dependencies. In this post, I summarize some commonly used commands that I find useful for working with git submodule. For the list of full commands, check the git submodule manual.

Add a submodule

To add a submodule, if it is the first time (that is, no submodule in the repository yet), under the root directory of the repository, run

git submodule init
git submodule status
git submodule add -f git@example.com/the-repo ./the-repo

which will add the new repository to ./the-repo.

To add other submodules, under the root directory of the repository, run

git submodule add -f git@example.com/the-repo ./the-repo

Get submodules

By default, a git clone will not clone the submodule repositories. You may do it during clone by specifying options or further clone submodules in a cloned repository.

During clone

--recuisive will clone the submodules repositories too.

git clone --recursive git@example.org:repo

In a cloned repository

If you have cloned a repository and would like clone all its submodules, run

git submodule update --init --recursive

Check out the master and update all submodules

foreach runs commands in each submodules. To check out the master and then git pull in each submodules:

git submodule foreach --recursive git checkout master
git submodule foreach --recursive git pull

Push the version changes to origin

You may update the repository to update the submodules’ commits used by the repository (such as, updated a depended library inclued as a submodule).

# cd the git repository first (not in submodule)
git commit -am 'submodule updated'
git push

Delete a submodule

To delete a submodule from a repository, first

git submodule deinit ./the-repo

to remove the submodule from the repository.

If you would like to remove the submodule directory and files too, run

git rm ./the-repo

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

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