版本回退需注意git revert和git reset的区别
1、git revert
git revert 撤销某次操作,此次操作之前和之后的 commit 和 history 都会保留,并且把这次撤销作为一次最新的提交。
git revert是提交一个新的版本,将需要revert的版本的内容再反向修改回去,版本会递增,不影响之前提交的内容。
1、当代码已经commit但没有push时,可使用如下命令操作:
git revert HEAD //撤销倒数第一次提交
git revert HEAD^ //撤销倒数第二次提交
git-revert HEAD~2 //撤销倒数第三次提交
git revert commit //(比如:fa042ce57ebbe5bb9c8db709f719cec2c58ee7ff)撤销指定的版本,撤销也会作为一次提交进
2、当代码已经commit并push时,可使用如下命令:
git revert HEAD~1 //代码回退到前一个版本
当回退有冲突时,需手动合并冲突并进行修改,再 commit 和 push。这相当于增加了一次新的提交并且版本库中有记录。
git reset
git reset 是撤销某次提交,但是此次之后的修改都会被退回到暂存区。除了默认的 mixed 模式,还有 soft 和 hard 模式。
1.如果我们的有两次 commit 但是没有 push 代码
git reset HEAD~1 //撤销前一次 commit,所有代码回到 Working Copy
2.假如我们有几次代码修改,并且都已经 push 到了版本库中。
git reset --hard HEAD~2 //本地的Wroking Copy回退到2个版本之前。
3.只回退某个指定文件到指定版本
git reset a4e215234aa4927c85693dca7b68e9976948a35e xxx
4.回退到指定版本
git reset --hard commitId(通过git log可查看提交的commitId)
3、使用详情
1、查看提交版本
git log
2、回退
这里我们假设应该回滚到239afed0857cc2e77c17c01014077808619af64d这个版本,及这个版本及之后的commit全部取消。
git reset --hard commit_id //退到/进到 指定commit的sha码 commit_id:239afed0857cc2e77c17c01014077808619af64d
3、重新提交代码
git commit a.txt -m "重新提交" // 记得不要提交不想提交的文件哦