切换·Esc 返回

工作树Worktree

Git 专区
为同一个项目建立多个文件夹,同时处理不同版本

工作树可以在不同文件夹里检出不同分支,适合保留当前半成品的同时处理另一项任务。移除目录前要先保存改动并停止运行中的服务,避免丢失未完成文件。

同一个仓库.git 只有一份
my-first-pagemain 分支,半成品原样放着
my-first-page-hotfixhotfix 分支,专心救火
$ git worktree add -b hotfix/login ../my-first-page-hotfix main
一个仓库长出两个并排的工作目录,各自检出不同分支、互不影响。救火不用 stash,主目录的半成品原样放着。

什么时候用

  • 用 git worktree add 创建对应分支的独立工作目录
    $ git worktree add -b hotfix/login ../my-first-page-hotfix mainPreparing worktree (new branch 'hotfix/login')HEAD is now at a1b2c3d 首页能跑了
  • 救火不用 stash:主目录半成品原样放着,去隔壁修完再回来
    📁 my-first-pagemain · 新首页改到一半,原样放着📁 my-first-page-hotfixhotfix/login · 专心救火
  • AI 多开并行:每个窗口占一个 worktree,各改各的分支不踩脚
    窗口 AAI 改 feat/nav 导航
    窗口 BAI 改 feat/pricing 定价页
    各占一个目录,互不踩脚
  • 确认目录干净并停止服务后,再用 worktree remove 清理
    $ git worktree remove ../my-first-page-hotfix$ git worktree list/Users/hu/my-first-page a1b2c3d [main]干净利落,只剩主目录

什么时候不用

  • 改到一半硬切分支救火:改动被带着跑,思路全断
    $ git checkout hotfix/loginerror: Your local changes would be overwritten by checkout.改到一半被迫打包,思路全断
  • worktree 开了一堆从不清理:磁盘和脑子一起乱
    $ git worktree listmy-first-page a1b2c3d [main]my-first-page-hotfix a1b2c3d [hotfix/login]my-first-page-test 0f1e2d3 [feat/test]my-first-page-old 9a8b7c6 [feat/old]开了一堆忘了删,磁盘和脑子都乱
  • 想让同一个分支在两个目录同时工作:Git 不允许,直接报错
    $ git worktree add ../dup mainfatal: 'main' is already checked out at '…/my-first-page'同一个分支同时只能在一个目录工作
  • 不要直接删除目录,应使用 worktree remove 更新 Git 记录
    📁 my-first-page-hotfix右键 → 移到废纸篓
    Git 还以为它在,list 里挂着一条尸体记录
组成结构 · Anatomy
🗄 同一个本地仓库(.git)历史和分支共用一份
📁 my-first-pagemain主工作目录 📁 my-first-page-hotfixhotfix/loginadd 出来的隔壁目录
1本地仓库Repository只有一份 .git:所有 worktree 共用同一套历史和分支
2主工作目录Main Worktree你平时干活的文件夹,check out 着 main
3链接工作目录Linked Worktreeworktree add 在隔壁开出的目录,check out 着另一条分支
常见变体 · Variants
新建分支目录Add
git worktree add -b hotfix/login ../hotfix main
要从 main 新开分支和工作目录时
查看清单List
git worktree list
忘了自己开过几份时查一下
用完清理Remove
git worktree remove ../hotfix
救完火、合完代码就收摊
典型使用场景
git worktree add 开目录
zsh — my-first-page
$ git worktree add -b hotfix/login ../my-first-page-hotfix main Preparing worktree (new branch 'hotfix/login') HEAD is now at a1b2c3d 首页能跑了 $ ls .. my-first-page my-first-page-hotfix 隔壁多了一份工作目录,共用同一个仓库历史
隔壁文件夹救火
📁 my-first-page
main
新首页改到一半
未提交的 3 个文件原样放着
📁 my-first-page-hotfix
hotfix/login
线上登录挂了
在这里修 → commit → push
AI 两个窗口并行改
窗口 A
AI 正在改导航栏
my-first-page-nav · feat/nav
运行中…
窗口 B
AI 正在改定价页
my-first-page-pricing · feat/pricing
运行中…
各占一个 worktree,改完各自开 PR,互不覆盖
list 查看与 remove 清理
zsh — my-first-page
$ git worktree list /Users/hu/my-first-page a1b2c3d [main] /Users/hu/my-first-page-hotfix e5f6a7b [hotfix/login] $ git worktree remove ../my-first-page-hotfix $ git worktree list /Users/hu/my-first-page a1b2c3d [main] 救完火,清理干净