持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第28天,点击查看活动详情
git checkout
官网中对 checkout 的说明是:checkout : Switch branches or restore working tree files。checkout :切换分支或者恢复工作树文件。
常用的两种用法:
用法1:切换分支
git checkout 命令允许在 git branch 创建的分支之间进行切换。所以可以先使用 git branch 创建一个新的分支,然后使用 git checkout 切换到该分支。
git branch <branch_name> // 创建分支
git checkout <branch_name> // 切换到新创建的分支上
git checkout 命令允许加 -b 的参数,功能就是上面两个命令的合并,不用使用 git branch 命令创建分支。它会自动创建一个新分支并立即切换到该分支上。
git checkout -b <new-branch>
以上的操作都是对本地的分支进行切换。但是在团队合作时,有时候需要使用远程仓库。而远程仓库的某些功能是在另外的分支上,你本地没有该分支。所以需要拉取远程所有的分支。
git fetch --all
拉取到远程仓库所有的分支后,然后就可以使用 git checkout -b 直接切换。如果不使用 git fetch。也可以直接使用git checkout 。
git checkout -b <branch_name> origin/<branch_name>
用法2:恢复文件
git checkout 恢复文件,仅仅恢复的是刚才修改的文件,且文件是未提交的。
git checkout -- [filepath] // 恢复某指定的文件
git checkout -- . // 恢复所有的文件
有时候想把当前的修改都撤回,恢复到某次提交的远程分支时,只需要使用 git reset 命令。
git reset --head origin/<branch_name>
git switch 和 git restore
在 Git 2.23 版本中新增加了2个命令:git switch 和 git restore 。它们的工作原理和 checkout 命令非常相似,但不是完全一致的。
在 Git 2.23 版本中将 checkout的命令分成两个命令代替它:
- switch :切换分支
- restore:恢复工作树分支
如果你想要切换分支时就可以这样使用:
git switch <branch_name>
// 等价于 git checkout <branch_name>
git switch -c <branch_name>
// 等价于 git checkout -
如果想要恢复一个文件时:
git restore ./aaa.js
// 等价于 git checkout -- ./aaa.js
git restore --staged ./aaa.js
//等价于 git reset HEAD ./aaa.js
所以,如果为避免混淆,在工作中可以使用目的明确的 switch 和 restore 命令。