git reset和git checkout之间的区别

时间:2015-01-02 12:45:03

标签: git git-checkout git-reset

以下两个命令的实际效果有何不同? 他们是否都使临时区域和工作目录与最新的提交相匹配?

git reset --hard

git checkout <sha-of-latest-commit>

2 个答案:

答案 0 :(得分:2)

git reset --hard会放弃对工作树中文件的所有更改。

git checkout <sha-of-latest-commit>保留这些更改。

当您的HEAD引用分支(不是分离的HEAD模式)时,还有另一个区别。

git checkout <sha-of-latest-commit>将分离HEAD。

git reset --hard不会分离HEAD。

答案 1 :(得分:0)

git reset --hard等同于git reset --hard HEAD,即它使您的分支指向HEAD(即NOP),并将索引和工作树重置为相同的内容。

具有文字sha1的

git checkout将进入分离头模式,即您将不再在您的分支上。它也不会改变工作树或索引。

亲眼看看:

$ git init
$ touch a b
$ git add .
$ git commit -m 1
$ echo 1 >a; echo 1 >b; git add a #do some changes
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   a

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   b

$ git reset --hard 
$ git status # still on master, changes are gone
On branch master
nothing to commit, working directory clean
$ echo 1 >a; echo 1 >b; git add a  #redo changes
$ git checkout HEAD@{0}
$ git status  #no longer on master, changes are still there
HEAD detached at be924ba
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   a

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   b