Git Worktree Add
一句话解释
git worktree add 为另一分支创建链接工作树,无需克隆即可并行处理多分支。
用大白话说
git worktree add 创建一个链接到同一仓库的额外工作目录,检出另一分支。无需克隆两次或 stash 切换分支,你有多个工作树——各在自己的分支——共享同一 .git 对象存储。这非常适合上下文切换而不丢失位置。例如你在 feature 分支有未提交工作并需在 main 修 bug。运行 git worktree add ../hotfix main,新目录 ../hotfix 出现并检出 main。你在那修 bug、推送、移除工作树——全不碰你的 feature 工作树。每个工作树有自有 HEAD 与索引但共享对象,故磁盘占用低。工作树与主工作树并存。用 git worktree list 列出、git worktree remove <path> 移除、git worktree prune 清理过期条目。适合在一分支跑长任务同时在另一分支继续,以及为构建保留干净 main 检出。
示例
bash
# Create a worktree for a hotfix on main, in a sibling dir
git worktree add ../project-hotfix main
# Now you have two working trees:
# ./project (on feature branch)
# ../project-hotfix (on main)
cd ../project-hotfix
git switch -c hotfix-123 # create hotfix branch here
# fix the bug, commit, push
git push origin hotfix-123
# Clean up when done
git worktree remove ../project-hotfix
git worktree list # shows remaining worktreesworktree add 在另一分支创建链接工作目录,共享对象存储。可同时处理两分支而无需 stash 或克隆。
相关术语
相关资源
相关课程
- Git Worktree
学习 git worktree。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。