git reset 回退commit提交的版本

-先模拟提交过程,一共提交四次,每次都向文本里写一个新数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 向文本中写入0
$ echo 0 >a.t
$ git add .
#第一次提交到仓库
$ git commit -m '0'
 
# 向文本中写入1
$ echo 1 >a.t
$ git add .;
#第二次提交到仓库
$ git commit -m '1'
 
# 向文本中写入2
$ echo 2 >a.t
$ git add .
#第三次提交到仓库
$ git commit -m '2'
 
# 向文本中写入3
$ echo 3 >a.t
$ git add .
#第四次提交到仓库
$ git commit -m '3'
 
# 显示提交过日志
$ git log

 

 

上图,(HEAD -> master) 代表当前所在提交版本的位置

 

查看文本内容:

 

 

HEAD 说明:

  • HEAD 表示当前版本

  • HEAD^ 上一个版本

  • HEAD^^ 上上一个版本

  • HEAD^^^ 上上上一个版本

  • 以此类推...

可以使用 ~数字表示

  • HEAD~0 表示当前版本

  • HEAD~1 上一个版本

  • HEAD^2 上上一个版本

  • HEAD^3 上上上一个版本

  • 以此类推...

 

-------------------------------------------   分割线  --------------------------------------------------------------

测试:每次回退一个版本

第一次执行 reset 回退

1
2
3
4
5
6
ubuntu@ubuntuE470:~/test$ git reset HEAD^
重置后取消暂存的变更:
M   a.t
ubuntu@ubuntuE470:~/test$ cat a.t
3
ubuntu@ubuntuE470:~/test$ git log

 -

 

第二次执行 reset 回退

1
2
3
4
5
6
ubuntu@ubuntuE470:~/test$ git reset HEAD^
重置后取消暂存的变更:
M   a.t
ubuntu@ubuntuE470:~/test$ cat a.t
3
ubuntu@ubuntuE470:~/test$ git log

 -

 

第三次执行 reset 回退

1
2
3
4
5
6
ubuntu@ubuntuE470:~/test$ git reset HEAD^
重置后取消暂存的变更:
M   a.t
ubuntu@ubuntuE470:~/test$ cat a.t
3
ubuntu@ubuntuE470:~/test$ git log

 -

 

总结:上面是每次回退一个版本,版本每次都在回退,但是内容一直是最后一次 commit 的 3

   如果使用 --hard 参数,内容也会跟着变化。

 

-------------------------------------------   分割线  --------------------------------------------------------------

测试: 直接回退到某次提交,用 --hard参数 覆盖当前内容(把 add 也撤销了)

1
2
3
4
5
$ git reset --hard d6cbefe0da132
HEAD 现在位于 d6cbefe 1
$ cat a.t
1
$ git log

 -

 

 注意:用 --hard 后 a.t 文本内容变成1 而原来的内容3被隐藏。彻底回退到某个版本,本地的源码也会变为上一个版本的内容

    如果还想找回 3 的内容,那就再输入 3 对应的 commit id  即可找回 内容3  对应的ID: c19972

 

 

-------------------------------------------   分割线  --------------------------------------------------------------

测试: 直接回退到某次提交,用 --soft 只回退 commit 内容,不回退文本内容

当前仓库状态

 

 

直接回退到指定 commit id :

1
2
3
4
5
$ cat a.t
3
$ git reset --soft f796337abab2
$ cat a.t
3

 -

 

 git reset --soft f796337abab2 和 git reset f796337abab2        效果是一样的

 

回退到某个版本,只回退了commit的信息,不会恢复到index file一级。

如果还要提交,直接commit即可。

1
2
3
4
5
6
$ echo 4 >a.t 
$ git add .
$ git commit -m '4'
[master a8016c2] 4
 1 file changed, 1 insertion(+), 1 deletion(-)
$ git log

 -

 

 

 

 

-

参考:

https://www.runoob.com/git/git-reset.html

https://hovertree.com/h/bjaf/dlxrxw5x.htm

https://www.freesion.com/article/3464516206/

posted @   悟透  阅读(131)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
历史上的今天:
2021-08-27 was全称
2021-08-27 curl访问https下载https文件
2021-08-27 Linux curl 命令下载文件
点击右上角即可分享
微信分享提示