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 不是独立仓库
相关推荐
BIBI204915 小时前
换 Git 托管平台怎么做?基于 TortoiseGit 的跨平台迁移教程
windows·git·tortoisegit·问题解决·版本控制·最佳实践
echome8881 天前
Git 日常救急:撤销提交、找回误删文件和解决冲突
git·版本控制
赵民勇1 天前
Git命令详解
git
不老刘2 天前
Antigravity 的 New Worktree 模式:给 AI 代理一个安全的“平行工位”
人工智能·git·ai编程·antigravity
光谱SpectrAI2 天前
Windows 也中招:Git Bash 和 Node 仍信任泄露的 eMudhra 证书
git
YIN_尹2 天前
【git原理与使用】git初识与安装
大数据·git·elasticsearch
Leo_Mr2 天前
Vue3 项目配置 Git 提交规范(企业通用方案:husky + commitlint + cz-git + lint-staged)
git
jyOverQ2 天前
Git rebase 和 merge 有什么区别?什么时候该用哪个?
git
晗夜未央2 天前
跨仓库 Skill 换台电脑就失效?用 Git remote 校验项目
人工智能·git·python
Lsetea2 天前
Git访问HTTPS证书不受信任:用URL级sslCAInfo限定私有CA范围
git·https·开发工具·ssl证书·ca证书