What is the difference between reset and revert in git
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.
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文件.
This article takes git bash as an example:
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:
File content:
At this point I will modify the file content to:
Creating a new branch is quick 1.
Make the first submission :
Submission record:
Submitted remote warehouse directory and file contents:
No problem, continue to modify the file content: Creating a new branch is quick 1 2., and make the second submission:
Now I will add a new test file and make the third submission:
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:
(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
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:
意思是告诉你,远程仓库代码较新,需要你执行 git pull
操作以同步代码,但这并不是我们的需求,所以我们不用理会,执行,git push -f
:
再看仓库:
历史记录只剩下了t1:
readme内容也得到了恢复:
可见,reset是彻彻底底的回退,该commit之后的所有修改将完全消失,包括提交记录。
优点:
- 彻底回退到指定版本,干净清爽;
- 提交时间线清晰,没有冗杂;
缺点:
- 记录彻底清除,无法再次恢复;
再说revert:
revert执行后会产生新的commit记录,是通过一次新的commit来恢复到之前旧的commit,但revert会保留恢复的该次提交后面的其它提交内容,假如后面的提交与要恢复的提交更改了同一地方,此时用revert就会产生冲突!
我们继续以上面的例子为例,我重新执行了t2和t3提交,恢复到reset之前的状态:
此时,我们按reset的思路,使用revert恢复到t1,执行命令:
git revert 8cbf16c0821d20fe42c361f4e3d75a0493dc5fc2
报错:
提示冲突了?让我们解决掉冲突后提交…
<<<<<<< HEAD Creating a new branch is quick 1 2. ======= Creating a new branch is quick. >>>>>>> parent of 8cbf16c (t1)
上面的冲突表示,当前的内容是:
Creating a new branch is quick 1 2.
而我们要恢复的内容是:
Creating a new branch is quick.
如果对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
执行后会自动进入编辑界面:
这里需要我们修改或输入提交日志,按 “i”,进入输入状态,写完后按ESC退出输入状态,再按“:wq”退出!
成功后,执行 git push:
查看仓库后台:
项目目录:
readme内容:
可见,revert操作成功后,产生了新的commit记录,t2对t1的修改已经恢复,现在的readme就是t1提交后的状态,但同时test文件仍然存在,即t3的提交不受影响!
Но если вы хотите удалить отправку t2t3 так же, как и сброс, то вы можете сначала вернуть t3, а затем отменить t2, что может достичь того же эффекта. Но в этом случае, почему бы не использовать сброс напрямую? ? Если вы хотите добиться эффекта сброса, а также хотите иметь запись, чтобы предотвратить сожаления, то вот оно. . . Это вопрос, над которым стоит задуматься!
Краткое описание разницы между git reset и revert:
- reset — это полный откат к указанной версии фиксации. commit Все коммиты будут очищены, включая историю коммитов;
- revert отменяет только изменение указанного коммита и не влияет на последующие коммиты. Однако, если отозванный коммит изменяется в том же месте последующим коммитом, произойдет ошибка.Конфликт;
- После выполнения сброса записи не будут созданы, но записи будут созданы после выполнения возврата;
- Невозможно восстановить после выполнения сброса, поскольку записи будут не очищается после выполнения возврата, и будут созданы новые записи, поэтому файл не будет потерян. Вы можете выполнить возврат несколько раз, чтобы восстановить состояние до определенного изменения;
- HEAD переместится назад после выполняется сброс, при этом HEAD revert всегда будет двигаться вперед;
После разъяснения основных принципов сброса и возврата вы поймете, какую команду в какое время уместнее использовать!
Советы: В инструменте разработки IDEA выберите файл, щелкните правой кнопкой мыши параметр git, и вы найдете Rollback:
Это следует отличать от сброса и возврата. Откат не относится к команде 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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,

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

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

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

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

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

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

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,
