How to use Git submodules to include external repositories?

To include external repositories using Git submodules, you can follow these steps:

  1. Initialize the main repository:

    • Create a new repository or navigate to the existing repository's location in your system.
    • Open the command line or terminal and navigate to the repository directory.
    • Initialize a new Git repository if it's not already initialized by running the command: git init
  2. Add a submodule:

    • Identify the external repository that you want to include as a submodule.
    • Get the URL of the external repository. You can find this on the repository's homepage.
    • In the command line or terminal, navigate to the root directory of your main repository.
    • Run the following command to add the submodule: git submodule add <URL of external repository>
      • For example: git submodule add https://github.com/example/repo.git
  3. Commit the changes:

    • Run the command: git commit -m "Added submodule <name>". Replace <name> with an appropriate name that represents the submodule you added.
  4. Update the submodule:

    • To retrieve the latest changes from the external repository, navigate inside the submodule directory in your local repository.
    • Run the command: git submodule update --remote
      • This fetches the latest changes from the submodule repository and updates it in your main repository.
  5. Commit and push:

    • After updating the submodule, navigate back to the root directory of your main repository.
    • Run the command: git commit -am "Updated submodule <name>" to commit and stage the changes.
    • Finally, push the changes to the remote repository using: git push

Now your main repository includes the external repository as a submodule. Other users can also clone your repository and update the submodule to get the latest changes from the external repository.