Submodules

Learn how to manage external repositories with Git submodules

Git Submodules

Git submodules allow you to include external Git repositories as subdirectories in your project while keeping their histories separate.

Adding Submodules

# Add submodule
git submodule add https://github.com/user/repo.git path/to/submodule

# Add submodule with specific branch
git submodule add -b main https://github.com/user/repo.git libs/external

# Commit submodule addition
git commit -m "Add external library as submodule"

Working with Submodules

Clone Repository with Submodules

# Clone and initialize submodules
git clone --recursive https://github.com/user/main-repo.git

# Or after cloning
git submodule update --init --recursive

Update Submodules

# Update to latest commit
git submodule update --remote

# Update specific submodule
git submodule update --remote path/to/submodule

Common Commands

Initialize Submodules

# Initialize submodules after clone
git submodule init

# Update to recorded commit
git submodule update

# Combined init and update
git submodule update --init

Status and Info

# Show submodule status
git submodule status

# Show submodule summary
git submodule summary

# List submodules
git submodule foreach 'echo $name'

Managing Submodules

Remove Submodule

# Remove from .gitmodules
git submodule deinit path/to/submodule

# Remove from .git/config
git rm path/to/submodule

# Commit changes
git commit -m "Remove submodule"

Update Submodule to Specific Commit

# Enter submodule directory
cd path/to/submodule

# Checkout specific commit
git checkout commit-hash

# Return to main project
cd ../..

# Commit submodule update
git add path/to/submodule
git commit -m "Update submodule to specific version"

Best Practices

  • Pin submodules to specific commits for stability
  • Document submodule purposes in README
  • Use relative URLs when possible
  • Regularly update submodules
  • Test after submodule updates

Common Issues

Submodule Not Updated

# Pull latest changes in main repo
git pull

# Update submodules to match
git submodule update --recursive

Detached HEAD in Submodule

# Create branch in submodule
cd path/to/submodule
git checkout -b feature-branch

Free Resources