git教程学习笔记(5)

git教程学习来自廖雪峰的官方网站

撤销修改

如果在readme.txt里写错了一行代码,比如

Git is a distributed  version control system. sound HAHAHA.
Git is free software distributed under the GPL.
我是来试验修改的
测试管理修改的
测试管理修改第二次的

今天天气好好啊,好想涨工资

最后一行自然不是代码内容,那除了手动删除代码中的错误行,那还有一种方法,使用git status先查看状态

$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   readme.txt

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

这里面明确说了一句话 

 (use "git restore <file>..." to discard changes in working directory)

可以使用 git restore + 文件名 可以丢弃工作区的修改

$ git restore readme.txt

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

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

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

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

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

Git is a distributed  version control system. sound HAHAHA.
Git is free software distributed under the GPL.
我是来试验修改的
测试管理修改的

文件内容果然复原了。

还有一种情况就是readme.txt已经添加到暂存区后,在commit提交之前,需要撤销,可以使用git restore -- staged 文件名 将其重新放回工作区

$ git status
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   readme.txt

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

$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   readme.txt

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

还记得如何丢弃工作区的修改吗?

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

整个世界终于清静了!

小结时间。

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

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

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

猜你喜欢

转载自www.cnblogs.com/LeoXnote/p/11460561.html