Git Submodule: Modular Way For Repositories


Steps with Examples:

1. Navigate to Your Repository

Open your terminal and navigate to the root directory of your repository:

cd /path/to/your/repo

For example:

cd ~/projects/my-main-repo

2. Add the Submodule

Use the git submodule add command to include another repository as a submodule:

git submodule add <repository-url> <path>

Example:

git submodule add https://github.com/example/library.git libs/library

Here:

  • https://github.com/example/library.git is the URL of the submodule repository.
  • libs/library is the directory where the submodule will be added.

3. Commit the Changes

After adding the submodule, commit the .gitmodules file and the new submodule directory.

git add .gitmodules libs/library
git commit -m "Add submodule: library"

4. Initialize and Update the Submodule

Fetch the contents of the submodule:

git submodule update --init --recursive

Additional Operations:

Update Submodules

To update the submodules to the latest version:

git submodule update --remote

Remove a Submodule

If you need to remove the submodule:

  1. Unstage and remove the submodule:
git rm --cached libs/library
  1. Remove the submodule directory:
rm -rf libs/library
  1. Delete the entry from .gitmodules:
git config -f .gitmodules --remove-section submodule.libs/library
  1. Commit the changes:
git add .gitmodules
git commit -m "Remove submodule: library"

This should guide you through adding, updating, and removing submodules with practical examples.

Leave a Reply

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

About the author

Engineering Manager of multiple projects.