git的撤销操做:reset、checkout和revert

概述

这三个命令均可以用于撤销。git

reset和checkout能够做用于commit或者文件,revert只能做用于commit。安全

commit级别的操做

reset

$ git checkout hotfix
$ git reset HEAD~2

git reset用于撤销未被提交到remote的改动,即撤销local的修改。除了移动当前分支的HEAD,还能够更改workspace和index:spa

  • --soft:修改HEAD,不修改index和workspace。指针

  • --mixed:修改HEAD和index,不修改workspace。默认行为。code

  • --hard:修改HEAD、index、workspace。
    rem

git reset --mixed HEAD把index的内容退回到workspace中。
git reset --hard HEAD把index和workspace的修改所有撤销。it

checkout

checkout做用于commit级别时,只是移动HEAD到不一样的commit。若是有unstaged的文件,git会阻止操做并提示。若是使用commit id做为参数,可能会致使野指针。table

revert

$ git checkout hotfix
$ git revert HEAD^^

revert经过新建一个commit来撤销一次commit所作的修改,是一种安全的方式,并无修改commit history。class

revert用于撤销committed changes,reset用于撤销uncommitted changes。file

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)
相关文章
相关标签/搜索