Last updated

The git submodule cheat sheet

A git submodule, in its essence, is a reference to another git repository. It’s a great way to include vendor code (like plugins or themes) into your own code base. This post contains some examples on how to use git submodules effectively.

Add a submodule

You need to know the remote git repository url and where you want to place that it in your repository.

1git submodule add https://example.com/submodule-repo.git path/to/submodule
2git add . 
3git commit -m "adds submodule path/to/submodule"

Cloning a project with submodules

When you clone a repository that contains submodules there are a few extra steps to be taken.

1git clone http://example.com/repo.git repo
2cd repo
3git submodule init
4git submodule update

If you’re sure you want to fetch all submodules (and their submodules), you can also use this fancy one-liner:

1git clone --recurse-submodules http://example.com/repo.git

Update your submodule

If you’re simply tracking the master branch for the submodule, you can suffice with a simple fetch and merge.

1cd path/to/submodule
2git fetch
3git merge origin/master

If you’re in a hurry, you can streamline this for all submodules in your repo with:

1git submodule update --remote --recursive

Don’t forget to commit this change to your own repo, so others are locked to this new version of the submodule as well.

Track a specific branch of version

The repo for your submodule may have a specific branch (e.g. stable) or tag you want to track, instead of master.

1git config -f .gitmodules submodule.path/to/submodule.branch stable
2git submodule update --remote

Again, don’t forget to commit your changes to .gitmodules to send this change to other contributors to you repository.

Remove a submodule

Removing a git submodule consists of two steps: removing the reference and removing the locally cached version.

1git submodule deinit path/to/submodule
2git rm path/to/submodule
3git commit -m "removes submodule path/to/submodule"
4
5rm -rf .git/modules/path/to/submodule

Bonus: see submodule status in git status

You can configure git to show a submodule summary when you do a git status. There is a small performance trade-off here, but it might be useful to you.

1git config status.submodulesummary 1
Tags: git