git worktree是 Git 自带的原生命令,从 Git 2.5(2015年)开始引入。
为什么需要它?
日常开发中你肯定遇到过这种场景:
你正在
feature-x分支写代码,写到一半,突然要紧急修一个线上 bug。你只能:
git stash→git checkout main→ 修 bug → 提交 →git checkout feature-x→git stash pop麻烦,而且容易丢东西。
Worktree 的解决方案:直接开一个新目录,在那里修 bug,原来的代码完全不动。
实际操作演示
你当前仓库可以直接试:
# 1. 查看当前 worktree(默认只有一个)
git worktree list
# 输出类似:
# /Users/markz/code/tools/json-助手-&-ai-修复 abc1234 [main]
# 2. 创建一个新 worktree,同时创建新分支
git worktree add ../json-hotfix -b hotfix-branch
# 这会:
# - 在上级目录创建 json-hotfix 文件夹
# - 基于当前 HEAD 创建 hotfix-branch 分支
# - 把该分支 checkout 到 json-hotfix 目录
# 3. 去新目录工作
cd ../json-hotfix
# 这里就是一个完整的工作目录,可以正常编辑、提交
# 4. 回到原目录,原来的代码完全没变
cd ../json-助手-\&-ai-修复
# 5. 用完了,删掉 worktree
git worktree remove ../json-hotfix完整命令速查
# 添加 worktree(checkout 已有分支)
git worktree add <路径> <分支名>
# 添加 worktree(同时创建新分支)
git worktree add <路径> -b <新分支名>
# 列出所有 worktree
git worktree list
# 删除 worktree
git worktree remove <路径>
# 清理已手动删除的 worktree 记录
git worktree prune和其他方案的对比
| 方案 | 优点 | 缺点 |
|---|---|---|
git stash + 切分支 | 不占额外空间 | 容易忘记 pop,操作繁琐 |
git clone 一份新仓库 | 完全隔离 | 重新克隆慢,.git占双倍空间 |
git worktree | 秒创建,共享.git,完全隔离 | 同一分支不能在两个 worktree 中同时 checkout |
注意事项
- 同一个分支不能同时被两个 worktree 使用 — 这是为了防止冲突
- 所有 worktree 共享同一个
.git数据库 — 在任何一个 worktree 里 commit,其他的都能看到 - 删除 worktree 目录前最好用
git worktree remove,不要直接rm -rf(如果手动删了,用git worktree prune清理记录)
适用场景
- 紧急修 bug,不想动当前开发中的代码
- 同时对比两个分支的运行效果
- CI/CD 中并行构建多个分支
- Code Review 时想本地跑另一个分支的代码
是个很实用但知名度不高的 Git 功能,值得加入日常工具箱。
更新: 2026-03-19 16:22:50
原文: https://www.yuque.com/dongpozhouzi-mshe3/zhm85g/lgmf3uhnh4fhzxpw