2.5.撤销修改

自然,你是不会犯错的。不过现在是凌晨两点,你正在赶一份工作报告,你在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.

(1)你只是在工作区写入了这句话,并未添加到暂存区。

这个错误可以很容易地纠正它。你完全可以手动删掉最后一行,这样问题便得到了解决。
我们这里要学习的是如何把该文件恢复到上一个版本的状态(放弃当前版本未提交的所有修改)。我们先用git status查看一下:

$ git status
On branch master
Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

        modified:   readme.txt

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

根据提示我们可以知道,使用git checkout -- ...可以放弃对工作区的所有修改。

$ git checkout -- readme.txt
$ git status
On branch master
nothing to commit, working tree clean

再来看一下文件的内容:

$ 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 tracked changes of files.

果然,文件被还原到了上个版本状态。

(2)假定是凌晨3点,你不但写了一些胡话,还添加到暂存区了:

我们先来执行一下checkout 方法

$ git checkout -- 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 tracked changes of files.
My stupid boss still prefers SVN.

可以看出,工作区中的修改依然还在,此时checkout未达到我们想要的效果。
实际上使用checkout分两种情况:

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

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

那么如何在修改添加到暂存区后将工作区和暂存区恢复到上个版本呢?
我们先git status查看下状态

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD ..." to unstage)

        modified:   readme.txt

果然,在这里我们找到了解决办法,提示告诉我们可以用git reset HEAD ...来清除暂存区的内容。

$ git reset head readme.txt
Unstaged changes after reset:
M       readme.txt

此时再来查看下状态:

$ git status
On branch master
Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

        modified:   readme.txt

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

提示可以看出暂存区中的内容以及清除,接下来可以对工作区中的修改进行提交或者还原,这样我们就把(2)中的问题转化为了(1)中的问题,接下来再使用checkout方法便可还原工作区。

(3)假设你不但改错了东西,还从暂存区提交到了版本库.

还记得版本回退一节吗?可以使用$ git reset --hard head^回退到上一个版本。不过,这是有条件的,就是你还没有把自己的本地版本库推送到远程。还记得Git是分布式版本控制系统吗?我们后面会讲到远程版本库,一旦你把stupid boss提交推送到远程版本库,你就真的惨了

你可能感兴趣的:(2.5.撤销修改)