From 2a5cd62aff871a9501a4d188c1a512e5c16214c6 Mon Sep 17 00:00:00 2001 From: Jack Lau Date: Mon, 30 Nov 2026 17:03:11 +0800 Subject: [PATCH] add git worktree usage doc - add/remove/list/move/lock commands - common parameters, scenarios and caveats - fix unclosed code fence in rebase section Signed-off-by: Jack Lau --- docs/Basic-Knowledge/Git_Command.md | 80 ++++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) diff --git a/docs/Basic-Knowledge/Git_Command.md b/docs/Basic-Knowledge/Git_Command.md index dee4531..252b500 100644 --- a/docs/Basic-Knowledge/Git_Command.md +++ b/docs/Basic-Knowledge/Git_Command.md @@ -829,8 +829,9 @@ git show ``` git add <冲突文件> git rebase --continue + ``` - #### 常用参数 +#### 常用参数 - `-i` 或 `--interactive`:进入交互式模式,可以编辑、合并或删除提交。 - `--continue`:在解决冲突后继续变基。 @@ -1160,6 +1161,83 @@ git config --global sendemail.smtpAuth LOGIN # Use LOGIN method git send-email --smtp-ssl --to ffmpeg-devel@ffmpeg.org --subject "[PATCH] Fix time_base handling" -1 b438672b11645e1152375beba759a0d2c704e3b1 ``` +## git worktree + +### 介绍 + +`git worktree` 让同一个仓库同时检出多个工作目录:各自有独立的 HEAD、暂存区和工作区,共享同一份提交对象和分支。适合并行开发、紧急修 bug、同时构建多个版本,不用 stash 切分支,也不用重复 clone。 + +Git 2.5+ 可用,`move`/`remove`/`lock` 需 Git 2.17+。 + +### 添加工作树 + +``` +# 检出已有分支(远程分支会自动创建同名本地分支) +git worktree add ../repo-feature feature +git worktree add ../repo-feature origin/feature + +# 新建分支并检出 +git worktree add -b hotfix/login ../repo-hotfix main + +# 分离头指针,临时看某个提交或标签 +git worktree add --detach ../repo-v1.2 v1.2.0 + +# 只创建工作树,暂不检出文件 +git worktree add --no-checkout ../repo-empty feature +``` + +### 查看工作树 + +``` +git worktree list +git worktree list --porcelain +``` + +### 删除工作树 + +``` +git worktree remove ../repo-feature # 有未提交修改时会拒绝 +git worktree remove -f ../repo-feature # 强制删除,未提交修改丢失 +git worktree prune # 清理手动 rm 后残留的记录 +``` + +### 移动与锁定 + +``` +git worktree move ../repo-feature ../new-place/repo-feature +git worktree lock ../repo-usb --reason "在移动硬盘上" +git worktree unlock ../repo-usb +``` + +不要手动 `mv` 工作树目录,指针会失效;已经 `mv` 过的可用 `git worktree repair` 修复。 + +### 常用参数 + +| 参数 | 说明 | +| :--- | :--- | +| `-b ` | 新建分支并检出 | +| `-B ` | 新建分支,已存在则重置(破坏性) | +| `--detach` | 分离头指针,不占用分支 | +| `--no-checkout` | 不检出文件 | +| `-f` / `--force` | 强制添加或删除 | +| `--lock` / `--reason` | 创建时锁定并记录原因 | + +### 使用场景 + +* 多个分支并行开发,改完切目录即可,不用等编译、不用 stash。 +* 紧急 hotfix:手头代码改到一半,另开一份干净目录修复线上问题。 +* 代码审查 / 复现问题:`--detach` 检出待审提交,看完直接删。 +* 一边跑构建一边改代码,或用两份工作树分别做 Debug/Release 构建。 + +### 注意事项 + +* 同一个分支默认只能被一个工作树检出;确实要多次检出用 `--force`,但两边提交会互相打架。 +* 分支和提交共享,工作区文件不共享:一个目录里 commit 后,其他目录要自己 `git pull`/`git reset`。 +* 新工作树不含子模块内容,需执行 `git submodule update --init --recursive`。 +* hooks 共享(位于主仓库 `.git/hooks`),对全部工作树生效。 +* 链接工作树里的 `.git` 是文本指针文件,不要手工删除或修改。 +* 删除目录请用 `git worktree remove`,直接 `rm -rf` 会留下残留记录,需要 `prune` 清理。 + ## git官网 \ No newline at end of file