git checkout 指令的几种经常使用方式

1. 切换分支

初始状态:git

head-to-master.png

执行命令:this

$ git checkout testing

head-to-testing.png

这条命令作了两件事。 一是使 HEAD 指向 master 分支,二是将工做目录恢复成 master 分支所指向的快照内容。spa

2. 建立并切换分支

$ git checkout -b iss53

这条命令是下面两条命令的简写:指针

$ git branch iss53
$ git checkout iss53

3. 分离头指针

3.1

现有一个仓库,当前在 master 分支上,有三次提交记录:code

$ git log --graph --all --oneline  --decorate
* 2950c9d (HEAD -> master) c
* a61ae27 b
* 1ef09c2 a

3.2

当你想作一些尝试性的更新,而且可能随时丢弃新增的代码时,能够将仓库处于分离头指针状态下。例如,我想在提交 b(a61ae27)基础下作试验:orm

$ git checkout a61ae27
Note: checking out 'a61ae27'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at a61ae27... b

3.3

查看分支列表,HEAD 指向了提交 b(a61ae27),处于分离头指针状态:blog

$ git branch
* (HEAD detached at)
  master

3.4

而后修改代码,而且添加到暂存区和提交它,此时 HEAD 指向了提交 d(d605ebb):get

$ git log --graph --all --oneline  --decorate
* d605ebb (HEAD) d
| * 2950c9d (master) c
|/
* a61ae27 b
* 1ef09c2 a

3.5

要注意的是,此时是没有任何东西正在引用提交 d(d605ebb),若是你此时切换到其余分支,那么这部分修改的代码会被 Git 垃圾回收it

3.6

若是你对你的试验满意,那么你能够经过建立一个分支或者标签指向提交 d(d605ebb)来保留修改的内容:io

$ git checkout -b foo

3.7

可是,若是你一不当心在新建分支以前切换了分支,使得修改的内容被 Git 回收了,也不用着急,能够经过 reflog 指令来找回提交 d(d605ebb):

$ git checkout master
Warning: you are leaving 1 commit behind, not connected to
any of your branches:

  d605ebb d

If you want to keep it by creating a new branch, this may be a good time
to do so with:

 git branch <new-branch-name> d605ebb

Switched to branch 'master'

其实你已经能够根据 Git 给出的提示直接建立新分支了。

$ git reflog
b990217 HEAD@{0}: checkout: moving from d605ebb783e029edb0193a6b6c9165c4e092462e to master
d605ebb HEAD@{1}: commit: d
a61ae27 HEAD@{2}: checkout: moving from master to a61ae27
2950c9d HEAD@{5}: commit: c
a61ae27 HEAD@{6}: commit: b
1ef09c2 HEAD@{7}: commit (initial): a

最后执行如下命令便可:

$ git checkout -b foo

4. 撤消对文件的修改

当你修改内容以后,却又不想保留,就能够使用如下命令来撤销:

$ git checkout -- file.text

注意:要加上 -- 表示撤销文件修改,来跟切换分支和分离头指针作区分。

5. 参考资料

相关文章
相关标签/搜索