Git - Git教程 06:撤销修改

撤销修改

1 - 给 file_D.txt 文件添加内容 hello asshole !

1 $ git status
2 On branch master
3 Changes not staged for commit:
4   (use "git add <file>..." to update what will be committed)
5   (use "git checkout -- <file>..." to discard changes in working directory)
6 
7     modified:   file_D.txt
8 
9 no changes added to commit (use "git add" and/or "git commit -a")

2 - 撤销新添加的内容

1 $ git checkout -- file_D.txt

git checkout -- xxx 意思是把 xxx 文件在工作区的修改全部撤销,分两种情况

第一种:xxx 文件自修改后还没有被放到暂存区,这时撤销修改就回到和版本库一模一样的状态

第二种:xxx 文件 已添加到了暂存区且作了修改,这时撤销修改就回到添加到暂存区后的状态

总之它就是让这个文件回到最近一次 git commit 或 git add 时的状态

3 - 现在 file_D.txt 文件中添加内容 Asshole !!后,执行 git add 命令

1 git add file_D.txt

4 - 在没有 commit 前,我们查看状态

1 $ git status
2 On branch master
3 Changes to be committed:
4   (use "git reset HEAD <file>..." to unstage)
5 
6     modified:   file_D.txt

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

1 $ git reset HEAD file_D.txt
2 Unstaged changes after reset:
3 M    file_D.txt

6 - 这时我们查看状态:暂存区是干净的,而工作区存在修改

1 $ git status
2 On branch master
3 Changes not staged for commit:
4   (use "git add <file>..." to update what will be committed)
5   (use "git checkout -- <file>..." to discard changes in working directory)
6 
7     modified:   file_D.txt
8 
9 no changes added to commit (use "git add" and/or "git commit -a")

7 - 丢弃工作区的修改,并查看状态

1 $ git checkout -- file_D.txt
2 $ git status
3 On branch master
4 nothing to commit, working tree clean

小结

1 - 假设你不但改错了东西,还从暂存区提交到了版本库,怎么办呢?版本回退啊,可以回退到上一个版本。不过,这是有条件的!就是你还没有把自己的本地版本库推送到远程。还记得 Git 是分布式版本控制系统吗?我们后面会讲到远程版本库,一旦你把新改动的内容 Asshole !!推送到远程版本库,那你就准备好纸巾使劲哭吧……

2 - 场景在线

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

② 场景B:当你不但改乱了工作区某个文件的内容,还添加到了暂存区时,想丢弃修改,分两步

    第一步用命令 git reset HEAD file 就回到了场景 A

    第二步重复场景 A 的步骤操作,即 git checkout -- fileName

③ 场景C:已经提交了不合适的修改到版本库时,想要撤销本次提交,就需要版本回退,前提是没有推送到远程库

posted on 2017-07-11 17:52  低头捡石頭  阅读(15)  评论(0编辑  收藏  举报

导航