Git Worktrees, Submodules, and Sparse Checkouts

Context switching between long-running feature branches and urgent production hotfixes often leads to messy git stash operations. git worktree allows you to check out multiple branches simultaneously into separate directories while sharing a single .git repository.


⚡ Quick Dive

Git Worktree vs. Stashing

Shared Repository (.git):
  ├── Main Directory:        /home/user/project (On branch: feature-checkout)
  └── Worktree Directory 1:  /home/user/project-hotfix (On branch: hotfix-auth)
  └── Worktree Directory 2:  /home/user/project-review (On branch: pr-982)
# Create a new linked worktree in a separate directory
git worktree add ../project-hotfix hotfix-auth

# List all active worktrees
git worktree list

# Remove worktree when hotfix is merged
git worktree remove ../project-hotfix

📖 Extended Guide

1. Managing Nested Repositories with git submodule

# Add external repo as submodule
git submodule add https://github.com/company/shared-proto.git proto/shared

# Initialize and clone submodules after cloning parent repository
git submodule update --init --recursive