0
0
GitHow-ToBeginner · 3 min read

How to Add Submodule in Git: Simple Steps and Examples

To add a submodule in Git, use the command git submodule add <repository-url> <path>. This adds another Git repository inside your current project, letting you track it separately.
📐

Syntax

The basic syntax to add a submodule is:

  • git submodule add <repository-url> <path>: Adds the submodule repository at the specified path inside your project.
  • <repository-url>: The URL of the Git repository you want to add as a submodule.
  • <path>: The folder path where the submodule will be placed in your project.
bash
git submodule add <repository-url> <path>
💻

Example

This example shows how to add a submodule from a GitHub repository into a folder named libs/example-lib inside your project.

bash
git submodule add https://github.com/example/example-lib.git libs/example-lib

# After adding, initialize and fetch the submodule content
git submodule update --init --recursive
Output
Cloning into 'libs/example-lib'... remote: Enumerating objects: 10, done. remote: Counting objects: 100% (10/10), done. remote: Compressing objects: 100% (8/8), done. remote: Total 100 (delta 2), reused 7 (delta 1), pack-reused 90 Receiving objects: 100% (100/100), 12.34 KiB | 1.23 MiB/s, done. Resolving deltas: 100% (30/30), done.
⚠️

Common Pitfalls

Common mistakes when adding submodules include:

  • Not specifying the path, which defaults to the repo name and may clutter your project structure.
  • Forgetting to run git submodule update --init --recursive after cloning a repo with submodules, leaving submodules empty.
  • Committing changes inside submodules without pushing them to their own remote repository.
  • Confusing submodules with subtrees; submodules track separate repositories, so you must manage them independently.
bash
## Wrong way: Adding submodule without path (defaults to repo name)
git submodule add https://github.com/example/example-lib.git

## Right way: Specify path clearly
git submodule add https://github.com/example/example-lib.git libs/example-lib
📊

Quick Reference

CommandDescription
git submodule add Add a new submodule at the given path
git submodule update --init --recursiveInitialize and fetch all submodules
git submodule statusShow current submodule commit status
git submodule foreach git pull origin mainUpdate all submodules to latest main branch

Key Takeaways

Use git submodule add <repo-url> <path> to add a submodule at a specific folder.
Always run git submodule update --init --recursive after cloning a repo with submodules.
Manage submodules as separate Git repositories with their own commits and pushes.
Specify the path explicitly to keep your project organized.
Check submodule status with git submodule status to track their commit versions.