1

1. 切换分支

初始状态:

head-to-master.png

执行命令:

$ git checkout testing

head-to-testing.png

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

2. 创建并切换分支

$ git checkout -b iss53

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

$ git branch iss53
$ git checkout iss53

3. 分离头指针

3.1

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

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

3.2

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

$ 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),处于分离头指针状态:

$ git branch
* (HEAD detached at)
  master

3.4

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

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

3.5

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

3.6

如果你对你的试验满意,那么你可以通过创建一个分支或者标签指向提交 d(d605ebb)来保留修改的内容:

$ 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. 参考资料


3santiago3
113 声望2 粉丝