Learn GitHub
$ gh ghadvancedgit.ghsubmodules

Submodules, Subtrees & Worktrees

4 learning objectives Β· 5 key terms Β· 5 commands Β· 1 diagrams Β· 5 quiz questions

$objectives

Submodules, Subtrees & Worktrees

Advanced Git

Module 3 of 5 Β· lesson 11 in this module

What you'll be able to do

  • Compose repositories from other repositories with submodules
  • Compare submodules, subtrees, and worktrees honestly
  • Work across multiple branches simultaneously with worktrees
  • Update, pin, and troubleshoot nested repository setups
$concept

The idea, in plain language

Big systems outgrow single repositories, and three mechanisms compose repos from repos. Submodules nest a pinned commit of another repository inside yours (a gitlink entry plus .gitmodules config) β€” exact versions, explicit updates, and the famous footguns: detached HEAD checkouts, forgotten --recurse-submodules clones, and commits pointing at unpushed submodule states.

Subtrees merge another repository's history into yours (readable with plain git, updatable via split), trading submodule precision for simplicity. Worktrees solve a different problem β€” checking out multiple branches at once into separate directories from one clone, ending stash gymnastics when reviews interrupt. Choose per need: pinned dependencies (submodules), vendored code you modify (subtrees), parallel branches (worktrees).

$key terms

Key terms

submodule
A nested repository pinned at one commit, recorded via gitlink plus .gitmodules.
gitlink
The special index entry pointing at the nested commit β€” what the superproject actually versions.
subtree
Merged foreign history living as an ordinary directory, updatable via subtree split/pull.
worktree
An additional checked-out working tree (branch) attached to one repository.
--recurse-submodules
The clone/update flag that actually fetches nested content instead of empty directories.
$steps

How it works, step by step

  1. 1
    Add a submodule

    git submodule add <url> vendor/lib pins the dependency at its current commit and records the mapping in .gitmodules β€” commit both.

    addbash
    git submodule add https://github.com/acme/logger.git vendor/logger
    git status  # shows .gitmodules + gitlink entry
    git commit -m "Vendor logger at v2.1"
  2. 2
    Clone with content

    Plain clones leave submodule directories empty; --recurse-submodules fetches nested content, and submodule update --init --recursive repairs existing clones.

    clonebash
    git clone --recurse-submodules <url>
    # or, in an existing clone:
    git submodule update --init --recursive
  3. 3
    Update deliberately

    Enter the submodule, pull or checkout the new version, return and commit the new gitlink β€” superproject and dependency advance as one reviewed change.

    updatebash
    cd vendor/logger && git pull origin main
    cd ../.. && git add vendor/logger
    git commit -m "Bump logger to v2.2"
  4. 4
    Work in parallel with worktrees

    git worktree add ../hotfix main creates a second checkout for reviews without touching current work; remove it when done.

    worktreesbash
    git worktree add ../hotfix origin/main
    git worktree list
    git worktree remove ../hotfix
  5. 5
    Consider subtrees for vendoring

    git subtree add --prefix=vendor/lib <url> main --squash merges foreign history readably; split and pull keep it current without submodule machinery.

    subtreebash
    git subtree add --prefix=vendor/lib https://github.com/acme/lib.git main --squash
$commands

Commands worth memorising

Every block below is copy-ready β€” use the Copy button, then paste it into your terminal. Expected output is shown underneath so you know what β€œworking” looks like.

add a dependency repobash
git submodule add https://github.com/acme/logger.git vendor/logger
Output
Cloning into 'vendor/logger'...
(use .gitmodules + gitlink to record it)

Commit .gitmodules and the gitlink together β€” one without the other breaks clones.

clone with nested contentbash
git clone --recurse-submodules <url>

Without the flag, submodule directories arrive empty and builds fail mysteriously.

check submodule statusbash
git submodule status
Output
 a1b2c3d vendor/logger (v2.1)

Leading space means initialized and matching; -/+ flags mean uninitialized or diverged.

parallel checkoutbash
git worktree add ../hotfix origin/main
Output
Preparing worktree (checking out origin/main)

A second branch checked out beside current work β€” no stash required.

list worktreesbash
git worktree list
Output
/repo  a1b2c3d [main]
/repo-hotfix  e4f5a6b [hotfix]

Shows every attached tree; prune stale metadata if directories were deleted by hand.

$diagrams

Workflow diagrams

Diagram 1Three ways to compose repositories

Different problems, different tools β€” pinning vs vendoring vs parallel checkouts.

Reading the diagram
  1. Dependencies you track but rarely edit: submodules.
  2. Foreign code you patch regularly: subtrees.
  3. Simultaneous branches: worktrees, always.
$example

Worked example

Reviewing an urgent fix while feature work stays untouched, with a vendored dependency alongside.

parallel review, vendored depbash
git worktree add ../hotfix origin/main
# review + test in ../hotfix, feature work undisturbed in ./
git worktree remove ../hotfix
git subtree pull --prefix=vendor/lib https://github.com/acme/lib.git main --squash
Output
Hotfix verified without stashing; vendored library updated in place with readable history.
1The worktree gives the hotfix a full directory β€” editor, tests, and all β€” beside uncommitted feature work.
2Verification happens in isolation; removal afterward leaves zero residue.
3The subtree pull merges upstream library changes as ordinary commits, reviewable like any other.
$use cases

Where you'll use it

β–ΈPinned third-party dependencies with explicit update commits.
β–ΈReviewing hotfixes without stashing feature work (worktrees).
β–ΈVendoring libraries you patch, with upstream merges via subtree.
β–ΈCI checkouts that must include nested content (--recurse-submodules).
$mistakes

Common mistakes

  • Cloning without --recurse-submodules, then debugging empty directories.
  • Committing a gitlink pointing at an unpushed submodule commit.
  • Working on a detached HEAD inside a submodule and losing the commits.
  • Deleting worktree directories by hand without worktree prune.
$best practices

Best practices

  • Commit .gitmodules and gitlinks together, always.
  • Update submodules deliberately: enter, pull, return, commit the pointer.
  • Prefer worktrees over stash for parallel branches.
  • Choose subtrees when you regularly modify the vendored code.
  • Prune worktree metadata after manual directory deletion.
$exercise

Hands-on exercise

Compose and parallelize

Nest a repo, update it deliberately, and review across worktrees.

  1. Create two practice repos; add one as a submodule of the other and push both.
  2. Clone the superproject fresh with and without --recurse-submodules; compare.
  3. Update the nested repo, then bump the superproject pointer in a reviewed commit.
  4. Open a worktree on another branch and make an isolated change there.
  5. Convert the pattern to a subtree in a scratch clone and compare histories.

πŸ’‘ Hint: git submodule status decodes every state: space (ok), - (uninitialized), + (diverged).

Done when: A pinned, updated, understood nesting plus one parallel-branch review without stashing.

$quiz

Checkpoint quiz

0 of 5 answered Β· 0 correct

  1. Multiple choiceQ1

    What does the superproject actually record for a submodule?

  2. Multiple choiceQ2

    Fresh clones show empty submodule directories. What was forgotten?

  3. True or falseQ3

    True or false: worktrees let you check out multiple branches simultaneously from one clone.

  4. TroubleshootingQ4

    Teammates see your superproject update fail CI on missing nested files. Most likely cause?

  5. Multiple choiceQ5

    When is a subtree preferable to a submodule?

$summary

Module summary

  • Submodules pin nested repositories via gitlinks plus .gitmodules.
  • Always clone/update with --recurse-submodules semantics in mind.
  • Update deliberately: enter, pull, return, commit the pointer.
  • Subtrees vendor modifiable code with merged history.
  • Worktrees give parallel branches without stashing.

Next up: Composition handled; next is finding when things broke β€” systematic debugging with bisect.

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Put the GitHub course to work: open one of the company-wise repositories and follow the workflow you just learned, branch to release.