上次详细讲了一下Git中的修改,今天主要学习一下撤销修改和删除文件。继续使用之前的文件huper.txt
,在里面添加一条错误的句子:
this boy is huper
and he's so stupid!
added version 1.
added version 2.
added version 3.
added stage test.
added change test append.
this is a wrong line!
这个时候既没有add
也没有commit
,如果我们使用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: huper.txt
no changes added to commit (use "git add" and/or "git commit -a")
就像之前看到的,里面会提示我们可以使用git checkout --
命令来撤销本次修改。我们来试一下:
Huper@DESKTOP-AT9MCJI MINGW64 /e/GitWarehouse/localgit (master)
$ git checkout -- huper.txt
Huper@DESKTOP-AT9MCJI MINGW64 /e/GitWarehouse/localgit (master)
$ cat huper.txt
this boy is huper
and he's so stupid!
added version 1.
added version 2.
added version 3.
added stage test.
added change test append.
可以发现工作区内的修改成功撤销。事实上git checkout -- <file>
的意思就是,把<file>
文件在工作区的修改全部撤销,这里有两种情况:
一种是<file>
自修改后还没有被放到暂存区,现在,撤销修改就回到和版本库一模一样的状态;
一种是<file>
已经添加到暂存区后,又作了修改,现在,撤销修改就回到添加到暂存区后的状态。
总之,就是让这个文件回到最近一次git commit
或git add
时的状态。另外,这里的--
选项非常重要,千万不能漏掉,否则这个命令意思就变了,之后将分支相关内容的话会讲到。
之前讲的都是工作区内的撤销,如果这里我们已经将修改添加到暂存区了呢?比如如下情况:
$ cat huper.txt
this boy is huper
and he's so stupid!
added version 1.
added version 2.
added version 3.
added stage test.
added change test append.
this is a wrong line!
$ git add huper.txt
使用git status
命令查看状态,你会发现git已经向你提供了 解决方案:
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: huper.txt
使用git reset HEAD
命令会退到版本库的HEAD
,也就是你最近一次commit
的版本:
$ git reset HEAD huper.txt
Unstaged changes after reset:
M huper.txt
这条命令执行以后,暂存区会被刷新,也就是我们现在的修改只剩下工作区的修改了,这下就好办了,直接使用之前的checkout --
命令来解决:
$ git checkout -- huper.txt
$ cat huper.txt
this boy is huper
and he's so stupid!
added version 1.
added version 2.
added version 3.
added stage test.
added change test append.
再次成功撤销,世界又清净了许多。
接下来学习删除文件的操作,之前在工作区新建过一个huper2.txt
的文件,就拿这个文件来练手吧。首先使用rm
将其直接删除,然后查看工作区状态:
$ rm huper2.txt
$ git status
On branch master
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
deleted: huper2.txt
no changes added to commit (use "git add" and/or "git commit -a")
还是有两种选择:
- 使用
git add
或者git rm
将改动添加到暂存区,然后使用commit
提交。 - 使用
git checkout --
撤销改动。
注意这里第一种里比以前多了一种选择,就是还可以使用git rm
命令,两者效果实际上是相同的,但是建议使用rm
,意思更加明确一点。
总结:
1.工作区的改动撤销:git checkout – <file>
2.暂存区的改动撤销:git reset HEAD <file> -> git checkout – <file>
reset是刷新暂存区,checkout是查看某个版本库里的内容,<file>选项指定作用域为某个具体文件。