git checkout
git
用法
git checkout <branch> | git checkout -b <new> | git checkout -- <file>既能切分支又能还原文件的旧命令,在 git 2.23 里拆成了 switch 和 restore;checkout -- <file> 会把未提交的改动彻底删掉。
常用选项
| 选项 | 含义 |
|---|---|
| -b <new> | create the branch and switch to it |
| -B <new> | create or reset it to the current commit |
| -- <file> | overwrite the file with the staged version, losing your edits |
| --track <remote>/<branch> | start a local branch that follows a remote one |
| --detach | sit on a commit with no branch attached |
| -f | throw away local changes to switch anyway |
示例
git checkout -b feature/loginbranches off the current commit and moves there
git checkout mainswitches branch, same as git switch main
git checkout -- src/app.tsdiscards uncommitted edits to that file; they are gone
难的地方在于撤销有好几种:把分支的指向挪走,和补一个反向提交,不是一回事。
怎么看
- 方括号 [ ] 表示这部分可以不写。
- 省略号 … 表示可以写多个。
- 选项区分大小写——有些命令里 -r 和 -R 不是一回事。
常见问题
Q. git checkout 是做什么的?
既能切分支又能还原文件的旧命令,在 git 2.23 里拆成了 switch 和 restore;checkout -- <file> 会把未提交的改动彻底删掉。
Q. 怎么写?
git checkout <branch> | git checkout -b <new> | git checkout -- <file> —— 方括号表示可以省略的部分。
Q. 值得记的选项有几个?
这里列了 6 个,完整列表在 man git。这条命令属于git。
相关命令
man 手册: man git-checkout