Home > Development Tools > git > body text

What is the difference between reset and revert in git

青灯夜游
Release: 2021-11-30 14:58:15
Original
25819 people have browsed it

Difference: 1. Reset is a complete rollback to the specified commit version, and all commits after the commit will be cleared; while revert only undoes the modification of the specified commit and does not affect subsequent commits. 2. No records will be generated after reset is executed, but records will be generated after revert is executed.

What is the difference between reset and revert in git

The operating environment of this tutorial: Windows 7 system, Git version 2.30.0, Dell G3 computer.

Git is our commonly used version management tool. When our team collaborates on development projects, various conflicts often occur due to modifications and submissions of code and files, as well as frequent changes in product requirements, resulting in We have to make the decision to roll back the version and withdraw the submission, so at this time, the reset and revert commands come in handy!

reset and revert both have the meaning of undoing and rolling back, but each has its own merits, and the difference is still very big, so which command to use must be decided based on the actual situation. This article is Let everyone understand the difference between the two, and then use the correct commands accurately and quickly to solve practical problems!

下面的例子中,我有3次提交:
初始状态,只有readme一个文件,内容为Creating a new branch is quick.
t1提交后状态:只有readme一个文件,内容修改为Creating a new branch is quick 1.
t2提交后状态:只有readme一个文件,内容修改为Creating a new branch is quick 1 2.
t3提交后状态:新增了test文件.
Copy after login

This article takes git bash as an example:

What is the difference between reset and revert in git
Let’s talk about reset first:

reset, Usage: git reset --hard commit, commit is the SHA1 generated after submission. After executing this command, the code will completely roll back to the state of this submission, the work staging area and this submission. Subsequent submissions will be completely cleared, including submission records!

Example:

The original project contains a Readme.txt file:
What is the difference between reset and revert in git
File content:
What is the difference between reset and revert in git
At this point I will modify the file content to:

Creating a new branch is quick 1.

Make the first submission :
What is the difference between reset and revert in git
Submission record:
What is the difference between reset and revert in git
Submitted remote warehouse directory and file contents:

What is the difference between reset and revert in gitWhat is the difference between reset and revert in git
No problem, continue to modify the file content: Creating a new branch is quick 1 2., and make the second submission:
What is the difference between reset and revert in git
Now I will add a new test file and make the third submission:
What is the difference between reset and revert in git
What is the difference between reset and revert in gitWhat is the difference between reset and revert in git

Okay, now the product requirements have changed The new functions (the second modification of the readme and the new test file) are no longer needed. It is required to go back to the first submission "t1". If we choose to use reset:

Position first The commit to t1 can be copied from the remote warehouse commit history, or you can use the command git log to view:

What is the difference between reset and revert in git
(Tips, if the last If ":" appears on one line, enter wq to exit and return to the command line!)

Copy commit and execute the command:

git reset --hard 8cbf16c0821d20fe42c361f4e3d75a0493dc5fc2
Copy after login

What is the difference between reset and revert in git

Prompt , HEAD has pointed to t1, but when you refresh the background, you find that there is no change. This is because we still need to perform a push, but what needs to be noted here is that the local code has returned to the old version, but the remote warehouse is a new version. It is inconsistent with the local one, so you will get an error when using git push. Here we need to use forced commit, git push -f, we can also use git status to check the current status:

What is the difference between reset and revert in git

意思是告诉你,远程仓库代码较新,需要你执行 git pull操作以同步代码,但这并不是我们的需求,所以我们不用理会,执行,git push -f

![What is the difference between reset and revert in git](https://img-blog.csdnimg.cn/94c3e93f6efe40b6a4d12d02eb05cd4d.png

再看仓库:

What is the difference between reset and revert in git

历史记录只剩下了t1:

What is the difference between reset and revert in git

readme内容也得到了恢复:

What is the difference between reset and revert in git

可见,reset是彻彻底底的回退,该commit之后的所有修改将完全消失,包括提交记录。

优点

  • 彻底回退到指定版本,干净清爽;
  • 提交时间线清晰,没有冗杂;

缺点

  • 记录彻底清除,无法再次恢复;

再说revert

revert执行后会产生新的commit记录,是通过一次新的commit来恢复到之前旧的commit,但revert会保留恢复的该次提交后面的其它提交内容,假如后面的提交与要恢复的提交更改了同一地方,此时用revert就会产生冲突!

我们继续以上面的例子为例,我重新执行了t2和t3提交,恢复到reset之前的状态:

What is the difference between reset and revert in git
What is the difference between reset and revert in git
此时,我们按reset的思路,使用revert恢复到t1,执行命令:

git revert 8cbf16c0821d20fe42c361f4e3d75a0493dc5fc2
Copy after login

报错:

What is the difference between reset and revert in git
提示冲突了?让我们解决掉冲突后提交…

<<<<<<< HEAD
Creating a new branch is quick 1 2.
=======
Creating a new branch is quick.
>>>>>>> parent of 8cbf16c (t1)
Copy after login

上面的冲突表示,当前的内容是:

Creating a new branch is quick 1 2.
Copy after login

而我们要恢复的内容是:

Creating a new branch is quick.
Copy after login

如果对revert命令没有深入了解的话,就可能会产生疑惑,为什么会冲突?而且我实际上是想像reset一样恢复或者说是回退到t1(这里要再次说明一下t1的状态:只有一个readme文件,且内容是Creating a new branch is quick 1),但为什么冲突提示要恢复到Creating a new branch is quick.???这不是初始状态吗?

其实,准确来说,revert是撤销/撤回/反提交的意思,我们不能按reset的思路理解,我们执行git revert t1,这么做其实结果是要撤销t1的提交,注意,仅仅是撤销t1的提交,把t1的修改恢复到t1之前也就是初始的状态,而不会影响t2,t3的提交。但如果t2,t3中修改了t1修改的同一地方,那么就会产生冲突,因为revert意图撤销t1的修改,但发现t2和t3把t1的修改再次修改了,此时,revert意图变得不清晰,因为它无法确定到底是应用你最新的修改,还是恢复到初始状态,这将由你来决定!

所以我们想要恢复t1的状态,那我们就应该撤销t2对t1的修改git revert t2

git revert fc4889dcb327cff9f8078db6a0d5c601b8e91ae9
Copy after login

执行后会自动进入编辑界面:

What is the difference between reset and revert in git

这里需要我们修改或输入提交日志,按 “i”,进入输入状态,写完后按ESC退出输入状态,再按“:wq”退出!

成功后,执行 git push:

What is the difference between reset and revert in git

查看仓库后台:

What is the difference between reset and revert in git

项目目录:

What is the difference between reset and revert in git

readme内容:

What is the difference between reset and revert in git

可见,revert操作成功后,产生了新的commit记录,t2对t1的修改已经恢复,现在的readme就是t1提交后的状态,但同时test文件仍然存在,即t3的提交不受影响!

Но если вы хотите удалить отправку t2t3 так же, как и сброс, то вы можете сначала вернуть t3, а затем отменить t2, что может достичь того же эффекта. Но в этом случае, почему бы не использовать сброс напрямую? ? Если вы хотите добиться эффекта сброса, а также хотите иметь запись, чтобы предотвратить сожаления, то вот оно. . . Это вопрос, над которым стоит задуматься!

Краткое описание разницы между git reset и revert:

  • reset — это полный откат к указанной версии фиксации. commit Все коммиты будут очищены, включая историю коммитов;
  • revert отменяет только изменение указанного коммита и не влияет на последующие коммиты. Однако, если отозванный коммит изменяется в том же месте последующим коммитом, произойдет ошибка.Конфликт;
  • После выполнения сброса записи не будут созданы, но записи будут созданы после выполнения возврата;
  • Невозможно восстановить после выполнения сброса, поскольку записи будут не очищается после выполнения возврата, и будут созданы новые записи, поэтому файл не будет потерян. Вы можете выполнить возврат несколько раз, чтобы восстановить состояние до определенного изменения;
  • HEAD переместится назад после выполняется сброс, при этом HEAD revert всегда будет двигаться вперед;

После разъяснения основных принципов сброса и возврата вы поймете, какую команду в какое время уместнее использовать!

Советы: В инструменте разработки IDEA выберите файл, щелкните правой кнопкой мыши параметр git, и вы найдете Rollback

What is the difference between reset and revert in git
Это следует отличать от сброса и возврата. Откат не относится к команде git. Его функция — восстановление после изменения файла или кода. но еще не зафиксировано.Когда состояние соответствует коду удаленного склада, можно выполнить операцию отката!

Рекомендуемое обучение: "Git Tutorial"

The above is the detailed content of What is the difference between reset and revert in git. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template