Description

Sometimes we have to include other Git repositories which are thrid-party repositories into our own Git repository. Git sumodules allow us to get it and track changes in several repositories via a centeral one. The extra repositories could be located anypwhere in a parent Git repository’s workspace and are configured through .gitsubmodules file located at the root of the parent repository.

Creating a submodule

Add a submodule

  • Clone a repository into the Local Folder as a submodule and initialize the submodule.
1
2
git add submodule add [URL to Git Repo] [Local Folder]
git submodule init
  • Similarly, we could clone a specific branch of the repository:
1
2
git add submodule -b [Branch] [URL to Git Repo] [Local Folder]
git submodule init

After executing the above commands, the .gitsubmodules file that records the inforamtion about sub-repositories will created in the root of the parent repository.

Checkout the status of submodules

Use git submodule command to checkout the status of submoules, if - exists before the hash, it means this submodule is not initialized yet.

1
2
3
4
git submodule

e33f854d3f51f5ebd771a68da05ad0371a3c0570 assets (heads/master)
-x5kyt51ogia51f5ebd771a68da05ad0371a3c0570 static

Update submodules

Use git submodule update (--remote) to pulls in new commits into the main repository and its submodules.

1
git submodule update --remote

Working with a repository with submodules

There two ways to clone a repository with submodules:

Clone repository step by step

  1. clone the parent repository
1
git clone [URL to Parent Git Repo]
  1. Checkout the submodule status
1
git submodule
  1. Initialize the submodule
1
git submodule init
  1. Update the submodule
1
git submodule update 

clone repository recursively

1
git clone --recursive [URL to Parent Git Repo]

If you already have cloned a repository and now want to load it’s submodules you have to use submodule update.

1
git submodule update --init --recursive

Delete submodules

In order to delete submodules correctly, we need to delete the folders manually.

  1. Delete the folder of submodules
1
2
git rm --cached [submodule]
rm -rf [submodule]
  1. Delete relevant configuration in .gitsubmodules
1
2
3
[submodule "[submodule]"]
path = [submodule]
url = [URL to Submodule Git Repo]
  1. Delete relevant configuration in .git/config
1
2
[submodule "[submodule]"]
url = [URL to Submodule Git Repo]
  1. Delete files in .git folder
1
rm -rf .git/modules/[submodule]

References