Home Development Tools git What is the difference between reset and revert in git

What is the difference between reset and revert in git

Nov 30, 2021 pm 02:57 PM
git reset

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the Grayscale Encryption Trust Funds? Common Grayscale Encryption Trust Funds Inventory What are the Grayscale Encryption Trust Funds? Common Grayscale Encryption Trust Funds Inventory Mar 05, 2025 pm 12:33 PM

Grayscale Investment: The channel for institutional investors to enter the cryptocurrency market. Grayscale Investment Company provides digital currency investment services to institutions and investors. It allows investors to indirectly participate in cryptocurrency investment through the form of trust funds. The company has launched several crypto trusts, which has attracted widespread market attention, but the impact of these funds on token prices varies significantly. This article will introduce in detail some of Grayscale's major crypto trust funds. Grayscale Major Crypto Trust Funds Available at a glance Grayscale Investment (founded by DigitalCurrencyGroup in 2013) manages a variety of crypto asset trust funds, providing institutional investors and high-net-worth individuals with compliant investment channels. Its main funds include: Zcash (ZEC), SOL,

Delphi Digital: How to change the new AI economy by parsing the new ElizaOS v2 architecture? Delphi Digital: How to change the new AI economy by parsing the new ElizaOS v2 architecture? Mar 04, 2025 pm 07:00 PM

ElizaOSv2: Empowering AI and leading the new economy of Web3. AI is evolving from auxiliary tools to independent entities. ElizaOSv2 plays a key role in it, which gives AI the ability to manage funds and operate Web3 businesses. This article will dive into the key innovations of ElizaOSv2 and how it shapes an AI-driven future economy. AI Automation: Going to independently operate ElizaOS was originally an AI framework focusing on Web3 automation. v1 version allows AI to interact with smart contracts and blockchain data, while v2 version achieves significant performance improvements. Instead of just executing simple instructions, AI can independently manage workflows, operate business and develop financial strategies. Architecture upgrade: Enhanced A

As top market makers enter the crypto market, what impact will Castle Securities have on the industry? As top market makers enter the crypto market, what impact will Castle Securities have on the industry? Mar 04, 2025 pm 08:03 PM

The entry of top market maker Castle Securities into Bitcoin market maker is a symbol of the maturity of the Bitcoin market and a key step for traditional financial forces to compete for future asset pricing power. At the same time, for retail investors, it may mean the gradual weakening of their voice. On February 25, according to Bloomberg, Citadel Securities is seeking to become a liquidity provider for cryptocurrencies. The company aims to join the list of market makers on various exchanges, including exchanges operated by CoinbaseGlobal, BinanceHoldings and Crypto.com, people familiar with the matter said. Once approved by the exchange, the company initially planned to set up a market maker team outside the United States. This move is not only a sign

Bitwise: Businesses Buy Bitcoin A Neglected Big Trend Bitwise: Businesses Buy Bitcoin A Neglected Big Trend Mar 05, 2025 pm 02:42 PM

Weekly Observation: Businesses Hoarding Bitcoin – A Brewing Change I often point out some overlooked market trends in weekly memos. MicroStrategy's move is a stark example. Many people may say, "MicroStrategy and MichaelSaylor are already well-known, what are you going to pay attention to?" This is true, but many investors regard it as a special case and ignore the deeper market forces behind it. This view is one-sided. In-depth research on the adoption of Bitcoin as a reserve asset in recent months shows that this is not an isolated case, but a major trend that is emerging. I predict that in the next 12-18 months, hundreds of companies will follow suit and buy large quantities of Bitcoin

Significantly surpassing SFT, the secret behind o1/DeepSeek-R1 can also be used in multimodal large models Significantly surpassing SFT, the secret behind o1/DeepSeek-R1 can also be used in multimodal large models Mar 12, 2025 pm 01:03 PM

Researchers from Shanghai Jiaotong University, Shanghai AILab and the Chinese University of Hong Kong have launched the Visual-RFT (Visual Enhancement Fine Tuning) open source project, which requires only a small amount of data to significantly improve the performance of visual language big model (LVLM). Visual-RFT cleverly combines DeepSeek-R1's rule-based reinforcement learning approach with OpenAI's reinforcement fine-tuning (RFT) paradigm, successfully extending this approach from the text field to the visual field. By designing corresponding rule rewards for tasks such as visual subcategorization and object detection, Visual-RFT overcomes the limitations of the DeepSeek-R1 method being limited to text, mathematical reasoning and other fields, providing a new way for LVLM training. Vis

Euzi Coin (EOS) price forecast: analysts' forecast for EOS prices in 2025-2050 Euzi Coin (EOS) price forecast: analysts' forecast for EOS prices in 2025-2050 Mar 03, 2025 pm 10:30 PM

EOS price forecast and investment analysis: Outlook for 2025-2050 EOS, as a blockchain platform aimed at promoting the development of decentralized applications (dApps) and smart contracts, has attracted much attention since its launch in 2018. It adopts a delegated proof of stake (DPoS) mechanism, which significantly improves transaction speed and network bandwidth. This article explores the future trend of EOS prices in depth and analyzes the factors that affect their prices to help investors make smarter decisions. Key Points: As of February 24, 2025, the EOS price was $0.6134. The highest price of EOS is $22.8904 (April 29, 2018), the lowest price

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Altcoin Investment Guide: Teach you how to pay money on the DEX Exchange, now is a good time to build positions at low prices Altcoin Investment Guide: Teach you how to pay money on the DEX Exchange, now is a good time to build positions at low prices Mar 05, 2025 am 09:45 AM

In the cold winter of 2018, I inspected the photovoltaic power station in the Gobi in Qinghai. In the cold wind of minus 20 degrees Celsius, the engineer pointed to the shutdown photovoltaic panels and said, "These are the legacy of the previous round of expansion. Only when the market is cleared will new technologies rise." Now looking at the Binance altcoin list, those long-term sideways K-line charts are very similar to the photovoltaic panel arrays that were back then. The crypto market is undergoing the same cycle as traditional industries. Just like the knockout match of the photovoltaic industry from 2012 to 2016, the CEX altcoin market has entered a cruel liquidation stage: the daily trading volume of many star projects in 2021 fell below 10 million US dollars, and the median market value shrank by more than 70% from its peak. This is just like the trajectory of photovoltaic, Internet and coal giants falling from high-priced stocks to low-priced stocks. But behind the cyclical cruelty,

See all articles