Git Submodule Simplified Tutorial
2024-07-26
For clarity, we will refer to the local main module as the main module, the main module’s GitHub repository as the main repository, the local submodule as the submodule, and the submodule’s GitHub repository as the sub-repository.
Adding Submodules and Sub-repositories
- Clone the main repository to your local machine:
1git clone <main_repo_url> - Add the submodule within the main module:
1git submodule add <submodule_url> <submodule_repo_name>- If the submodule is successfully added, you will see a submodule folder inside the main module’s directory and a
.gitmodulesfile. Opening.gitmodules, you’ll find the stored information about your submodule and sub-repository.
- If the submodule is successfully added, you will see a submodule folder inside the main module’s directory and a
- Push the local files of the main module to GitHub
Updating Submodules and Sub-repositories
Updates to the main repository and sub-repository do not automatically synchronize, so manual synchronization is required. Here are the two common scenarios:
Updating the Main Repository Based on the Sub-repository
- If changes have been made to the submodule and pushed to the sub-repository, update the submodule in the main module with the following command:
This will synchronize the local files with the latest submodule files.
1git submodule update --remote - Push the updates to the main repository
Updating the Sub-repository Based on Main Repository
- In the local submodule directory, use the following command to update the submodule:
This will update the local files based on the files committed in the main repository.
1git submodule update - Push the updates to the sub-repository
Removing Submodules and Sub-repositories
- Deinitialize the submodule:
1git submodule deinit <submodule-name> - Remove the submodule directory:
1git rm -r <submodule-name> - Delete the submodule-related files in the
.gitdirectory (from the main module directory):Note: You can use the1rm -rf .git/modules/<submodule-name>-foption to force deletion if necessary.