Clone a Repository With Its Submodules

If is a first-time clone:

git clone --recursive <...>

If is an existing repository:

git submodule update --init

Add a Submodule

git submodule add <repo_url> [<path>]

Running this command will:

This clone will be a very full clone, which means not so many configs can play a role.

Pull Upstream Changes

Two ways:

Pulling upstream will also update the recorded hashes. Don't forget to commit changes.

Change Settings of Submodules

There're two paths available:

Change working directory into one of them, then any git commands will apply to the submodule. For the first path, if is not been cloned, commands would still apply to the top-level repository. It is recommended to open a new terminal tab/window for changes within a submodule.

What can do in a submodule:

What can NOT do (or not be recommended) in a submodule:

Change Tracking Branch

A submodule can only be tracked with a remote named branch, not a hash, not a local branch.

1. Update Branch Setting

Warning: <module> must match the name in .gitmodules .

If want to remove this setting (means to use the default branch):

2. Switch to the New Branch

git submodule update --remote [<path>]

This command will:

  1. do a git pull; git checkout origin/<remote-branch> in submodules
  2. update recorded hash (checked with status. See git submodule status)

Don't forget to commit changes.

Change Submodule URL

Mostly the same as Change Tracking Branch , but change url = <URL> line instead.

Move a Submodule to a New Path

git mv /path/to/submodule /new/path

git mv handles everything.

Remove a Submodule From Current Repository

  1. git submodule deinit /path/to/submodule : unregister submodule from .git/config
  2. remove .git/modules/path/to/submodule manually
  3. git rm /path/to/submodule : remove submodule folder, unregister from .gitmodules and stage changes

Reference

Submodule Command Explanation

Full Documentation | Example Usage

git submodule -h

List all sub-commands.

git submodule

Same as git submodule status without parameters.

git submodule status

List all submodules with paths and current hashes. Hashes may have a prefix:

git submodule add

Add a new submodule. See Add a Submodule .

git submodule init/deinit

(Un)register a submodule. "Registered" means "active". update and other sub-commands will only apply to active submodules.

git submodule update

Checkout the recorded hash of submodules. Some options:

git submodule foreach <command>

Run <command> within each submodule. Example: git submodule foreach git pull .

Published under Creative Commons Attribution-ShareAlike (CC-BY-SA) license. Feel free to comment or share :)