git的撤銷操作:reset、checkout和revert 區別

精講鏈接:
https://segmentfault.com/a/1190000009126517

 

這三個命令都可以用於撤銷。

reset和checkout可以作用於commit或者文件,revert只能作用於commit。
 

Index空間,也叫做stage空間,或者cache空間 

reset

$ git checkout hotfix
$ git reset HEAD~2

git reset 用於撤銷未被提交到remote的改動,即撤銷local的修改。
除了移動當前分支的HEAD,還可以更改workspace和index:

  • --soft:修改HEAD,不修改index和workspace。(只修改指針)

  • --mixed:修改HEAD和index,不修改workspace。默認行爲。(修改指針、暫存區)

  • --hard:修改HEAD、index、workspace。(修改指針、暫存區、工作區)

git reset --mixed HEAD 把index的內容退回到workspace中。
git reset --hard HEAD 把index和workspace的修改全部撤銷。

 

checkout

checkout作用於commit級別時,只是移動HEAD到不同的commit。如果有unstaged的文件,git會阻止操作並提示。如果使用commit id作爲參數,可能會導致野指針。

 

revert

revert通過新建一個commit來撤銷一次commit所做的修改,是一種安全的方式,並沒有修改commit history。

區別:revert用於撤銷committed changes,reset用於撤銷uncommitted changes。

 

 

file級別的操作

reset

git reset <commit> <filename>只修改index去匹配某次commit。

git reset HEAD filename把文件從index退回workspace,並將更改保存在workspace中。

checkout

git checkout <commit> <filename>只修改workspace去匹配某次commit。

git checkout HEAD filename抹掉文件在workspace的修改。

總結

Command Scope Common use cases
git reset Commit-level Discard commits in a private branch or throw away uncommited changes
git reset File-level Unstage a file
git checkout Commit-level Switch between branches or inspect old snapshots
git checkout File-level Discard changes in the working directory
git revert Commit-level Undo commits in a public branch
git revert File-level (N/A)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章