回顾:上一篇我们讲到了如何查看提交历史,学会了git log命令的使用,但是在工作的时候,我们经常会误改文件问题,所以这篇主要来讲如何撤销我们之前的提交。
我先创建了一个git.txt文件,并且在里面添加了一行boss is smart,我们通过cat命令查看一下
$ cat git.txt
boss is so smart
然后再修改文件添加一句话:i love you ,再次查看下当前文件
$ cat git.txt
boss is smart
I love you
撤销操作分为两种:
- 已经提交到了版本库,撤销回到上一个版本库
回到上一个版本库:
^一个指的是上一个版本,HEAD~10表示上十个版本
$ git reset --hard HEAD^
HEAD is now at f5881e4 git.txt
//查看一下当前文件 发现少了 i love you 回到了之前的版本
$ cat git.txt
boss is smart
但是假如我想回到指定版本呢???我们需要通过git log 打印出提交历史,gitlog忘记使用的小伙伴可以看这篇哦——史上最简单的git教程|第四篇:查看提交历史-git log的使用。前面的一串英文加数字其实是commit ID ,你每次提交都会产生这个ID。
//git log --pretty=oneline
d7cf4e47d37a632a8daddb5606e1fa681bb8aae7 (HEAD -> master)
f5881e45ba013b486f58322a9ca894f7a39974c2 git.txt
通过具体commit ID号回退到想回的版本
$ git reset --hard f5881e45ba013b486f58322a9ca894f7a39974c2
//再次查看git文件 发现真的回到了初始版本
$ cat git.txt
boss is smart
看到这是否会有一个疑问 :假如找不到commit ID 了呢,比如你关掉了git bach ,不用担心再来学一个新的命令: git reflog 他会打印出commit 记录 ,前面就是简写的commit ID
- 工作区的内容修改之后并添加到了暂存区,但是没有commit到版本库。
//重新新建了hello.txt 并git add 进入到 暂存区
打印日志查看当前状态 git status
$ git status
On branch master
Changes to be committed: (这句英文表示在暂存区,等待提交到版本库)
(use "git reset HEAD <file>..." to unstage)
modified: hello.txt
那么我们如何将这部分内容从暂存区中移除到工作区呢?
$ git reset HEAD hello.txt
Unstaged changes after reset:
M hello.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: hello.txt
所以我们得想法抛弃工作区的修改:
$ git checkout -- hello.txt
再次查看一下状态:
$ git status
On branch master
nothing to commit, working tree clean
终于清理干净了工作区。成功。
上一篇:史上最简单的git教程|第四篇:查看提交历史-git log的使用
下一篇:史上最简单的git教程|第六篇:谨慎删除git文件