一、工作区的内容你修改了多次,并且保存了多次,如果想回到修改前怎么办?
例一:对工作区的README.txt文件做了4次修改,且每次都做了保存
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
My
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
My stupid
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
My stupid boss
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
My stupid boss still prefers SVN
- 方法一:直接手动删掉后悔修改的内容,
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告诉我们可以通过git checkout -- <file>
命令删除丢弃工作区的修改
- 方法二:命令
git checkout -- <file>
丢弃工作区修改
$ cat README.txt
1Git is a distributed version control system
2Git is free sofware distributed under the GPL
3Git tracks changes of file
$ git checkout -- README.txt
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
git checkout -- <file>
的理解?
命令git checkout -- README.txt
意思就是,把readme.txt文件在工作区的修改全部撤销,这里有两种情况:
一种是readme.txt修改后还没有被放到暂存区,现在,撤销修改就回到和版本库一模一样的状态;
一种是readme.txt已经添加到暂存区后,又作了修改,现在,撤销修改就回到添加到暂存区后的状态。
总之,就是让这个文件回到最近一次git commit或git add时的状态
二、如果将修改git add
到了暂存区,又后悔git add
了怎么撤回?
例二:对README.txt增加了add,且添加到了暂存区
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
add
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: README.txt
Git告诉我们,用命令git reset HEAD <file>
撤销暂存区的修改,放到工作区
- 执行
git reset HEAD <file>
命令
$ 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 <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 -- <file>
命令放弃工作区修改
$ git checkout -- README.txt
$ git status
On branch master
nothing to commit, working tree clean
现在,假设你不但改错了东西,还从暂存区提交到了版本库,怎么办呢?还记得版本回退一节吗?可以回退到上一个版本。不过,这是有条件的,就是你还没有把自己的本地版本库推送到远程。还记得Git是分布式版本控制系统吗?我们后面会讲到远程版本库,一旦你把“stupid boss”提交推送到远程版本库,你就真的惨了……
小结
又到了小结时间。
场景1:当你改乱了工作区某个文件的内容,想直接丢弃工作区的修改时,用命令git checkout -- file
。
场景2:当你不但改乱了工作区某个文件的内容,还添加到了暂存区时,想丢弃修改,分两步,第一步用命令git reset HEAD file
,就回到了场景1,第二步按场景1操作。
场景3:已经提交了不合适的修改到版本库时,想要撤销本次提交,参考版本回退一节,不过前提是没有推送到远程库。
附图