Introduction

Working with Git submodules allows you to include other Git repositories within your own repository. This can be useful for managing external dependencies or including code from other projects. In this article we shall see how to work with Git submodules:

1. Adding a git submodule to your project:

To add a submodule to your Git repository, use the git submodule add command:

git submodule add <repository_url> <path_to_submodule_directory>

For example:

git submodule add https://github.com/example/repo.git my-submodule

This will clone the submodule repository into the specified directory (my-submodule in this case) and add it to your main repository.

2. Initialize and Update Submodules:

After adding a submodule, you need to initialize and update the submodule:

3. Working with Submodules:

Think of it this way: Submodules are like independent Git repositories. You can navigate into the submodule directory and work with it just like any other Git repository.

  • To enter the submodule:
cd <path_to_submodule_directory>
  • To update the submodule to the latest commit:
git pull
  • Make your changes within the submodule and commit them.

4. Commit the Submodule Reference:

When you commit changes to your main repository that include the submodule, it only records the reference to the submodule, not the actual files. To commit the reference, run:

git add .
git commit -m "Updated the submodule reference"

5. Cloning a Repository with Submodules:

If you clone a repository that has submodules, you need to initialize and update the submodules by running:

git submodule init
git submodule update

6. Update Submodules:

To update the submodules within an existing repository, you can use:

git submodule update --recursive --remote

This will update all submodules to the latest commit.

7. Removing a Submodule:

If you want to remove a submodule, follow these steps:

  • Delete the submodule directory:
rm -rf <path_to_submodule_directory>
  • Remove the submodule reference from the main repository:
git rm <path_to_submodule_directory>

Commit the change:

git commit -m "Removed submodule"

Working with Git submodules can be a bit complex, so make sure to document and communicate their use within your project to avoid confusion among collaborators.


Found this article helpful? You may follow me on Twitter where I tweet about interesting topics on software development.