TIL: How to manage Git submodules

How to manage Git submodules: initialize, update or remove them, checkout specific commit or tag, track selected branch and persist changes in a parent repository.

The working directory must contain already initiated Git repository, so use git init or just clone some existing repository.

Add submodule

The following command adds an existing Git submodule to a folder inside a selected destination or repository root (if destination is not specified).

1
git submodule add <submodule url> [destination]

URL pointing to a submodule is mandatory, destination – optional.

This will also create .gitmodules file in the repository root. That file contains detailed information about all the installed submodules.

Persist changes

When you check git status you will notice there are new files: .gitmodules and a file representing the submodule repository you added. Perform a commit so that gitlink in the parent repository is updated and (optionally) push the changes.

1
2
git commit --all --message "Added ... submodule"
git push

Change submodule version

By default, submodules track HEAD of the master branch, but will NOT be updated as you update your primary repository.

In order to update a submodule to the latest available version run:

1
git submodule update --rebase --remote

In order to make the submodule track a particular commit, specific tag or different branch change directory to the submodule folder and switch branches just like you would in a normal repo.

1
2
3
4
5
6
7
cd <submodule path>

# checkout using branch
git checkout -b <branch name> origin/<branch name>

# checkout using tag
git checkout tags/<tag_name> -b <branch_name>

Finally, remember to persist changes in a parent (root) repository.

1
2
git commit --all --message "Updated ... submodule"
git push

Remove submodule

Unfortunately, right now Git does not have a built-in way to remove submodules, it needs to be done manually. Hopefully this will be resolved in the future.

1
2
3
4
5
6
7
8
9
# remove entry from .git/config
git submodule deinit -f <submodule path>

# remove entry from .gitmodules
git rm -f <submodule path>

# remove submodule directories
rm -rf .git/modules/<submodule path>
rm -rf <submodule path>

Again, remember to persist changes.

1
2
git commit --all --message "Removed ... submodule"
git push

References


This entry is a part of my Today I Learned (TIL) series, in which I take and share short notes on what I have recently learned.

Load Comments?