Git 技巧:恢复到前一次提交 (图示分析)

本文详细介绍了使用Git撤销并回滚至初始状态的过程,包括创建分支、移动HEAD指针、软性重置以及最终提交更改。通过实例演示了如何在Git中实现这一操作,为开发者提供了实用的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对这篇文章的试验:http://www.oschina.net/translate/git-tips-revert-with-new-commit, FYI
prerequisites:
git init test
cd test
touch first.txt
git add .
git commit -m "intial commit." (生成commit id: 3c21c9c)
touch second.txt
git add.
git commit -m "2nd commit.",(生成commit id: 3c55cf4)



step1:
git branch revert-branch HEAD^ (新建branch,指向HEAD的前一次commit:3c21c9c)

step2:
git checkout revert-branch(移动HEAD指针到新的branch,同时用HEAD所指的commit覆盖index及working directory)
注:以上两步可以合并成一步git checkout -b revert-branch HEAD^


step3:
git reset --soft master(移动当前branch的head及HEAD到master所指的位置,index及working dir保持不变)


此时执行git status会看到如下结果:

$ git status
# On branch revert-branch
# Changes to be committed:
#   (use  to unstage)
#
#       deleted:    second.txt
#


step4:
git commit -m "reverted to initial state."(提交index/staging area的数据到commit history)


step 5:
git checkout master(移动HEAD指针到master分支)


step 6:
git merge revert-branch(执行fast-forward merge)

Let's verify:


Note:
git reset --soft|--mixed|--hard commitID

如果对文中提及的概念不是很清楚的, 请看这里: http://www.cnblogs.com/kidsitcn/p/4513297.html

转载于:https://my.oschina.net/uniquejava/blog/206606

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值