1. Home
  2. Blog
  3. DevOps

DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Both commands undo work, but in opposite ways. Reset rewrites history; revert adds to it. We built a small repository and ran every command to show exactly what each one does.

9 min read
Git reset vs revert: how to undo commits safely, with a tested example

Key takeaways

  • git revert creates a new commit that undoes an earlier one. History is kept, so it is safe on shared branches.
  • git reset moves the branch pointer backwards, removing commits from the branch. Use it on local work you have not pushed.
  • --soft keeps changes staged, --mixed keeps them unstaged, --hard throws them away.
  • Committed work lost to a reset can usually be recovered with git reflog. Uncommitted work cannot.

You committed a bug, or a whole wrong approach, and you want it gone. Git gives you two main tools, and choosing the wrong one on a shared branch can disrupt the whole team. The difference comes down to one question: do you want to add an undo to history, or rewrite history as if the mistake never happened?

We built a small repository with Git 2.56 and ran every command below. The commit hashes and outputs are from that run, so yours will differ. New to Git? Start with our Git tutorial.

The short answer

git revert git reset
What it does Adds a new commit with the opposite changes Moves the branch to an earlier commit
History Preserved Rewritten
Safe after pushing? Yes Not on shared branches
Can target an old commit only Yes No, it removes everything after the target
Typical use Undo a change already on main Tidy up local commits before pushing

Our test repository

We made four commits, each adding one file:

$ git log --oneline
17e3cba D: add cart
e48227b C: enable debug (bug)
74369ab B: add login
0cbab47 A: add home page

Commit C turned on debug mode by mistake. Commit D, which came after it, is good work we want to keep. This is the realistic case: the bad commit is not the latest one.

git revert: undo by adding a commit

$ git revert --no-edit HEAD~1
$ git log --oneline
5d8c654 Revert "C: enable debug (bug)"
17e3cba D: add cart
...

$ git show --stat HEAD
 config.js | 1 -
 1 file changed, 1 deletion(-)

Git worked out the opposite of commit C, removing config.js, and recorded it as a new commit. Commit D and its cart.js file stayed untouched. Nobody’s history changed, so anyone who already pulled can simply pull again. That is why revert is the right tool for anything already pushed.

If later commits changed the same lines as the reverted one, Git stops with a conflict, just as in a merge. Resolve it, then run git revert --continue, or git revert --abort to back out.

git reset: undo by moving the branch

Reset moves your current branch to another commit. Everything after that commit disappears from the branch. Unlike revert, it cannot surgically remove C while keeping D; it removes both. What happens to their file changes depends on the mode.

Soft, mixed and hard

We reset two commits back, to B, in each mode, restoring the repository in between.

–soft: keep changes staged

$ git reset --soft HEAD~2
$ git log --oneline
74369ab B: add login
0cbab47 A: add home page
$ git status --short
A  cart.js
A  config.js

The commits are gone, but their changes are still staged and ready to commit again. This is perfect for squashing several messy local commits into one clean commit.

–mixed (the default): keep changes unstaged

$ git reset HEAD~2
$ git status --short
?? cart.js
?? config.js

The changes stay in your working folder but are no longer staged. Use this to redo commits differently, for example to split one large commit into several smaller ones.

–hard: discard everything

$ git reset --hard HEAD~2
$ git log --oneline
74369ab B: add login
0cbab47 A: add home page
$ ls
index.html  login.js

cart.js and config.js were deleted from the folder too. This is the dangerous mode. It also discards uncommitted edits: we added a line to a tracked file, ran git reset --hard, and the line was gone without any warning.

Mode Branch moves Staging area Working files
--soft Yes Kept Kept
--mixed Yes Reset Kept
--hard Yes Reset Reset

Recovering with reflog

After our hard reset, commits C and D looked lost. They were not. Git keeps a log of where HEAD has pointed:

$ git reflog -4
74369ab HEAD@{0}: reset: moving to HEAD~2
17e3cba HEAD@{1}: reset: moving to HEAD@{1}
...

$ git reset --hard HEAD@{1}
$ git log --oneline
17e3cba D: add cart
e48227b C: enable debug (bug)
...

Both commits and their files came back. The reflog is local to your machine, and entries expire after a while (by default, 90 days for reachable entries and 30 days for unreachable ones), so recover sooner rather than later. It cannot save edits that were never committed.

Tip: Before any risky reset or rebase, create a backup branch with git branch backup-before-reset. It costs nothing and gives you an obvious way back.

Why reset is dangerous on shared branches

We pushed our branch to a remote, reset it back one commit locally, and tried to push again:

$ git push origin main
 ! [rejected]        main -> main (non-fast-forward)
error: failed to push some refs to '../remote.git'

Git refused because the remote has a commit that our branch no longer contains. Forcing it with git push --force would overwrite the remote, and every teammate who already pulled that commit would have a history that no longer matches. If you truly must rewrite a pushed branch, such as your own feature branch, use git push --force-with-lease, which refuses if someone else pushed in the meantime. On main or any branch others use, use revert instead. Many teams enforce this with branch protection rules.

Reverting a merge commit

Merges have two parents, so Git needs to know which side to keep:

$ git revert HEAD
error: commit a166a4b... is a merge but no -m option was given.

$ git revert -m 1 HEAD
$ git log --oneline
6eeb57d Revert "M: merge payments"
a166a4b M: merge payments
d28bd4b E: add payments

-m 1 means “keep the first parent”, which is the branch you merged into, usually main. The payments file was removed. One catch to know: if you later try to merge the same feature branch again, Git considers those commits already merged and will not bring the changes back. You must revert the revert first. Our guide to merge vs rebase explains how merge history works.

Undoing files, not commits

Sometimes you only want to undo changes to a file:

  • Unstage a file: git restore --staged notes.txt, or the older git reset notes.txt. In our test, a staged file (A) became untracked (??) again.
  • Discard edits to a file: git restore notes.txt. This cannot be undone.
  • Fix the last commit message or add a forgotten file: git commit --amend, only before pushing.
  • Get an old version of one file: git restore --source=HEAD~3 config.js.

Which one to use

Situation Command
Bad commit is already on main git revert <commit>
Squash local commits before a pull request git reset --soft, then commit
Split a commit you have not pushed git reset HEAD~1
Throw away local experiments git reset --hard (after a backup branch)
Undo a merged feature on main git revert -m 1 <merge>
Recover after a bad reset git reflog, then git reset --hard HEAD@{n}

Our Git commands cheat sheet lists these alongside other everyday commands.

Reverting several commits at once

A feature built over three commits, B, C and D, needs to come out of main. You can revert a range and record it as a single commit:

$ git revert --no-commit HEAD~2..HEAD
$ git commit -m "Revert feature"
$ git log --oneline
2917743 Revert feature
eedf9f0 D: finish feature
8d1ef91 C: more feature
85b42e8 B: start feature
945b819 A: base
$ ls
a.txt  b.txt

Look at the files. b.txt is still there. We reverted C and D, but not B, because a range like X..Y means “commits after X, up to Y”. HEAD~2..HEAD therefore covers only the last two commits. To include B, the range must start one commit earlier, at HEAD~3, or you can list the commits by hash. Check with git log --oneline HEAD~3..HEAD before reverting, so you can see exactly which commits the range includes.

--no-commit stages all the undo changes together so you can review them and commit once, which keeps history tidy. Git applies the reverts newest first, which reduces conflicts when the commits touch the same files.

Final thoughts

Revert is the polite undo: it records the fix in history and keeps everyone in sync. Reset is the private undo: powerful for cleaning up local work, harmful on shared branches. Learn the three reset modes, make a backup branch before anything risky, and remember that the reflog can usually rescue committed work.

Frequently asked questions

What is the difference between git reset and git revert?

git revert adds a new commit that undoes an earlier commit, keeping history. git reset moves the branch back to an earlier commit, removing later commits from it.

Is git revert safe on a pushed branch?

Yes. It only adds a commit, so teammates can pull it normally. It is the recommended way to undo changes on shared branches.

What does git reset –hard do?

It moves the branch and discards all staged and unstaged changes, making your files match the target commit. Uncommitted work is lost permanently.

Can I undo a git reset –hard?

For committed work, usually yes. Find the old commit in git reflog and reset to it. Edits that were never committed cannot be recovered.

How do I revert a merge commit?

Use git revert -m 1 <merge-commit>, where -m 1 keeps the main line. Remember to revert the revert if you later merge the same branch again.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →