2017-03-10<Git撤销修改>

Git撤销修改

撤销修改分为两种情况:

一种是readme.txt自修改后还没有被放到暂存区,现在,撤销修改就回到和版本库一模一样的状态;

一种是readme.txt已经添加到暂存区后,又作了修改,现在,撤销修改就回到添加到暂存区后的状态。

总之,就是让这个文件回到最近一次git commitgit add时的状态。

情况一:工作区修改还未放到暂存区

添加一条my stu...........

$ cat readme.txt

Git is a distributed version control system.

Git is free software distributed under the GPL.

Git has a mutable index called stage.

Git tracks changes of files.

My stupid boss still prefers SVN.

查看状态no changes...........暂存区是干净的

$ git status# On branch master# 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:   readme.txt#

no changes added to commit (use "git add" and/or "git commit -a")

Git会告诉你,git checkout -- file可以丢弃工作区的修改:

$ git checkout -- readme.txt

现在,看看readme.txt的文件内容:

$ cat readme.txt

Git is a distributed version control system.

Git is free software distributed under the GPL.

Git has a mutable index called stage.

Git tracks changes of files.

文件复原了!!

情况二:修改后放到暂存区还没提交

$ cat readme.txtGit is a distributed version control system.Git is free software distributed under the GPL.Git has a mutable index called stage.Git tracks changes of files.My stupid boss still prefers SVN.

$ git add readme.txt

查看状态还未提交

$ git status# On branch master# Changes to be committed:#   (use "git reset HEAD <file>..." to unstage)##       modified:   readme.txt#

Git同样告诉我们,用命令git reset HEAD file可以把暂存区的修改撤销掉(unstage),重新放回工作区:

$ git reset HEAD readme.txt

Unstaged changes after reset:

M       readme.txt

git reset命令既可以回退版本,也可以把暂存区的修改回退到工作区。当我们用HEAD时,表示最新的版本。

git status查看一下,现在暂存区是干净的,工作区有修改:

$ git status# On branch master# 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:   readme.txt#

no changes added to commit (use "git add" and/or "git commit -a")

丢弃工作区的修改吗?

$ git checkout -- readme.txt

$ git status# On branch master

nothing to commit (working directory clean)

小结

场景1:当你改乱了工作区某个文件的内容,想直接丢弃工作区的修改时,用命令git checkout -- file

场景2:当你不但改乱了工作区某个文件的内容,还添加到了暂存区时,想丢弃修改,分两步,第一步用命令git reset HEAD file,就回到了场景1,第二步按场景1操作。

场景3:已经提交了不合适的修改到版本库时,想要撤销本次提交,参考版本回退一节,不过前提是没有推送到远程库。

原文地址:https://www.cnblogs.com/livelihood/p/6538732.html