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 不是独立仓库
相关推荐
小此方21 小时前
「插曲:Git」企业规范篇:DevOps开发模型、Git Flow五类分支设计与测试/预发布/生产环境Bug修复及Hotfix紧急发布流程
git·bug·devops
溪语流沙21 小时前
【Web全栈进阶】JWT无状态认证:签发、校验、刷新
前端·git·python·github
OsDepK1 天前
osgit纯图形化git版本管理工具,多人开发团队协作工具,支持Mac与Windows
git
Madison-No71 天前
Git版本控制工具(一)
git
小小小米粒2 天前
重置本地git
大数据·git·elasticsearch
鶴哥只手遮天2 天前
第 8 章 工作区与检出:unpack-trees 与并行 checkout
git
xing-xing2 天前
git 相关命令总结
git
A-刘晨阳2 天前
GitLab + ArgoCD 实现 Kubernetes GitOps 自动化部署
运维·人工智能·git·kubernetes·自动化·云计算·argocd
ControlRookie2 天前
SyncBridge:一个 CODESYS 工程与 AI 之间工程师级的同步工具
git·ai编程·codesys·工业软件·controlrookie
鬼手点金3 天前
opencode-性能优化建议
java·人工智能·git·自动化·nanogpt