Git教程-撤销修改

Git教程-撤销修改

    • 撤销修改(丢弃工作区中的修改,没有add到暂存区)
    • 撤销修改(修改已经add到暂存区了)

撤销修改(丢弃工作区中的修改,没有add到暂存区)

当前的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.

对其做修改后:

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.

发现错误,想要删掉最后一行,返回到上一次的状态,可以手动删除readme.txt的最后一行,再重新提交
Git会告诉你,git checkout – file可以丢弃工作区的修改

命令git checkout – readme.txt意思就是,把readme.txt文件在工作区的修改全部撤销,这里有两种情况:

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

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

总之,就是让这个文件回到最近一次git commit或git add时的状态。
操作一遍理解下:

开始的readme.txt已经git commit了,第二次修改没有git add,此时的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会告诉你,git checkout – file可以丢弃工作区的修改
此时用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 tracks changes.

再查看git status

$ git status
On branch master
nothing to commit, working tree clean

撤销修改(修改已经add到暂存区了)

当前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.

修改后并且已经add到暂存区的内容:

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.

在commit之前,用git status查看:

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

        modified:   readme.txt

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

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

再用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 -- readme.txt丢弃掉工作区中的修改:

$ git status
On branch master
nothing to commit, working tree clean

你可能感兴趣的:(Git教程-撤销修改)