首页·终端命令

git worktree

git

用法

git worktree add <path> [<branch>]

从同一个仓库再签出一个工作目录,不用重新克隆就能同时开两个分支;同一个分支不能被签出两次,手动删掉目录后条目要等 prune 才清掉。

常用选项

选项含义
add <path> <branch>check that branch out into another folder
add -b <new> <path>create a branch and check it out there
listshow every working tree of this repository
remove <path>delete a working tree cleanly
pruneforget trees whose folder you deleted by hand
--detachcheck out a commit without a branch

示例

git worktree add ../hotfix hotfix/login

a second folder on another branch, sharing one .git

git worktree add -b release ../rel main

creates release from main in ../rel

git worktree remove ../hotfix

removes the folder and its bookkeeping entry

难的地方在于撤销有好几种:把分支的指向挪走,和补一个反向提交,不是一回事。

怎么看

  • 方括号 [ ] 表示这部分可以不写。
  • 省略号 … 表示可以写多个。
  • 选项区分大小写——有些命令里 -r 和 -R 不是一回事。

常见问题

Q. git worktree 是做什么的?

从同一个仓库再签出一个工作目录,不用重新克隆就能同时开两个分支;同一个分支不能被签出两次,手动删掉目录后条目要等 prune 才清掉。

Q. 怎么写?

git worktree add <path> [<branch>] —— 方括号表示可以省略的部分。

Q. 值得记的选项有几个?

这里列了 6 个,完整列表在 man git。这条命令属于git。

相关命令

man 手册: man git-worktree