git worktree
允许同时检出多个分支到不同目录,无需切换分支或使用 stash
语法
git worktree <subcommand> [<options>]
参数
| 参数 | 说明 | 示例 | 级别 |
|---|---|---|---|
add <path> [<branch>] |
创建新的工作区并检出指定分支 | |
常用 |
list |
列出所有工作区 | |
常用 |
remove <worktree> |
删除指定工作区 | |
常用 |
prune |
清理无效的工作区引用 | |
常用 |
add -b <new-branch> <path> |
创建新分支并在新工作区中检出 | |
常用 |
示例
在相邻目录检出 hotfix 分支
git worktree add ../hotfix-branch hotfix/login
创建新分支并在新目录中工作
git worktree add -b feature/new ../feature-work
查看所有工作区
git worktree list
/home/user/project abc1234 [main]
/home/user/hotfix-branch def5678 [hotfix/login]
删除不再需要的工作区
git worktree remove ../hotfix-branch
清理已手动删除目录的工作区记录
git worktree prune
技巧
- 适合需要同时在多个分支工作的场景(如边修 bug 边开发新功能)
- 比 git stash + checkout 更高效,不会打断当前工作流
- 所有工作区共享同一个 .git 仓库,节省磁盘空间
- 工作区用完后记得 remove,避免占用磁盘空间