Git Worktree详解介绍

在日常开发中,我们经常遇到这样的场景:

  • 当前分支正在开发功能 A,但突然要修紧急 bug
  • 需要同时对比两个分支的代码
  • 想在不切换当前工作目录的情况下并行开发
  • build / test 需要在不同分支同时进行

第一想法就是git stash + git checkout 来回切分支,或者clone 一个目录,但 Git 早就提供了一个更优雅的能力:git worktree

一、Git Worktree 是什么?

Git Worktree 是 Git 提供的一种能力:允许一个 Git 仓库(.git)关联多个工作目录(working tree)。

复制代码
project-main/        (main branch)
project-feature/     (feature branch)
project-hotfix/      (hotfix branch)

它们:

  • 共享同一个 .git
  • 但每个目录可以 checkout 不同分支
  • 互不影响

二、核心价值

1. 不再频繁 stash / checkout

避免:

  • git stash
  • git checkout
  • git stash pop

worktree方式:

shell 复制代码
git worktree add ../hotfix hotfix

2. 并行开发

多个 IDE 同时打开不同分支:

  • IntelliJ:feature 分支
  • VSCode:hotfix 分支
  • Terminal:release 分支

互不干扰。


3. 避免重复 clone

不用多次 git clone,一个仓库即可。


4. CI/CD 友好

例如:

  • 一个目录跑 build
  • 一个目录跑 test
  • 一个目录跑 benchmark

避免 checkout 互相污染。


三、原理

  • .git 是唯一的
  • worktree 是多个工作目录
  • Git 通过 gitdir 关联
shell 复制代码
repo/
  .git (主仓库)

../feature/
  .git -> repo/.git/worktrees/feature

四、常用命令

1. 查看

shell 复制代码
git worktree list

2. 创建

shell 复制代码
git worktree add <path> <branch>

# 1、在 ../feature 创建工作目录
# 2、checkout feature 分支
git worktree add ../feature feature

3. 创建新分支

shell 复制代码
git worktree add -b new-feature ../new-feature main

#1、从 main 创建新分支 new-feature
#2、在新目录 checkout 

4. 删除

shell 复制代码
git worktree remove <path>

#1、目录必须没有未提交修改
#2、否则需要 --force

5. 清理

shell 复制代码
#用于清理 Git 内部残留记录。
git worktree prune

6. 锁定

shell 复制代码
# 锁定
git worktree lock <path>
# 解锁
git worktree unlock ../feature

五、应用场景

1. 紧急修 bug

feature 开发中 → hotfix 并行处理

传统方式:

  • stash
  • 切分支
  • 修 bug
  • 再切回来

worktree

shell 复制代码
git worktree add ../hotfix hotfix

2. 多版本维护

v1 / v2 / v3 并行维护

shell 复制代码
git worktree add ../v1 v1.0
git worktree add ../v2 v2.0
git worktree add ../v3 v3.0

3. 多环境对比

不同分支同时运行对比行为

shell 复制代码
git worktree add ../main main
git worktree add ../feature feature

4. CI 构建

避免重复 clone,加速构建


六、注意事项

  • 同一分支不能同时 checkout 多个 worktree
  • 删除必须 git worktree remove
  • 不要直接 rm -rf
  • worktree 不是独立仓库
相关推荐
胖大和尚2 小时前
当前仓库推送到同一台机器上的另一个文件夹
git
轮到我狗叫了1 天前
git - 版本控制工具 - 对应的常见命令 - 以及无需后续每次手动source conda
git
changxiang1 天前
GIT 备忘
git
DogDaoDao2 天前
Windows 开发提效工具全景指南:60+ 工具的工程化分层配置
windows·git·程序员·开发工具·powershell·everything·msys2
wdfk_prog2 天前
GitHub push 失败:如何扫描并清理 Git 历史中的大文件
git·elasticsearch·github
大明二代2 天前
使用 Traefik、cert-manager 和 DNS-01 为内网 Kubernetes 服务配置 HTTPS
git·kubernetes·flux
小芒果_012 天前
git常用命令速查
大数据·git·elasticsearch
2501_930472442 天前
腾讯云助手规范化Git提交记录
git·elasticsearch·腾讯云
风尘小子3 天前
git的.gitignore文件中文件和目录配置
git