Git checkout

Git checkout

git checkout 检出命令,可以用来切换分支查看某个 commit 的代码等。

detached HEAD

当你执行 git checkout [commitId] 时,你会看到下面的文件警告:

Note: switching to '467dd6520'.

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 switching back to a branch.

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

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 467dd65 version 3

这代表什么意思?什么叫做 detached HEAD ?执行命令 .git/HEAD 查看一下 HEAD 头指针的指向就会明白。

$ cat .git/HEAD
ref: refs/heads/master

# 检出到某一个 commitId
$ git checkout 467dd6520
$ cat .git/HEAD
467dd6520221c270098166e2be6389fbb2c3b1b9

原来 detached HEAD 指的是 HEAD 头指针指向了一个具体的 commitId,而不是一个分支(引用)。

切换分支

切换到 branch-xxx 分支,且暂存区和工作区的文件也会跟着变动:

git checkout branch-xxx

撤销本地修改

本地对某个文件做了修改,现在要恢复到修改之前的状态:

git checkout -- fileName

撤销本地所有文件的修改:

git checkout -- .
# 或
git checkout .

创建并切换到新分支

git checkout -b newBranchName

使用 -B 可以强制创建某个分支,并覆盖掉本地已经存在的分支,慎用!

扫描下面二维码,在手机端阅读: