Git submodules let you include one Git repository inside another. They’re super useful when you need to use external code in your project while keeping it up to date. Let’s learn how to use them step by step.
What is a Git Submodule?
A Git submodule is simply a Git repository inside another Git repository. Think of it like having a folder in your project that’s actually another complete project with its own history and files.
Adding Your First Submodule
To add a submodule, use this command:
git submodule add https://github.com/example/library.git lib/library
This creates a new folder called ‘lib/library’ in your project. It also creates a ‘.gitmodules’ file that keeps track of all your submodules.
Getting a Project with Submodules
When you clone a project that has submodules, you have two options:
Option 1 – Get everything at once:
git clone --recursive https://github.com/example/project.git
Option 2 – Get the submodules after cloning:
git clone https://github.com/example/project.git
git submodule init
git submodule update
Updating Submodules
To get the newest version of a submodule:
# Update all submodules
git submodule update --remote
# Update just one submodule
git submodule update --remote lib/library
# Make sure you have everything
git submodule update --init --recursive
Making Changes in Submodules
When you want to change something in a submodule:
# Go into the submodule
cd lib/library
# Create a new branch
git checkout -b new-feature
# Make changes and save them
git add .
git commit -m "Added new feature"
git push origin new-feature
# Go back to main project
cd ..
git add lib/library
git commit -m "Updated submodule"
Checking Submodule Status
To see what’s happening with your submodules:
# Check status
git submodule status
# Get updates from all submodules
git submodule foreach git fetch
Working with Specific Versions
It’s good practice to use specific versions of submodules:
cd lib/library
git checkout v2.1.0
cd ..
git add lib/library
git commit -m "Using version 2.1.0"
Removing Submodules
If you need to remove a submodule:
git submodule deinit -f lib/library
git rm -f lib/library
git commit -m "Removed library"
Fixing Common Problems
If a submodule is stuck or broken:
git submodule sync
git submodule update --init --recursive