Lesson 09 intermediate

Undoing Changes in Git

Pick the right undo for every situation: git restore for files, git commit --amend, git reset soft, mixed and hard, git revert for shared history, git clean for untracked files, the reflog safety net and the new git history command for rewording, splitting, fixing and dropping commits.

Everybody makes mistakes in Git: the wrong file committed, a debug line pushed, a branch reset too far. The good news is that almost everything in Git can be undone, as long as you pick the right tool. The confusing part is that there are several tools, and each works on a different area: the working tree, the staging area, your local commits or shared history.

First, find out where you are

Before undoing anything, look:

$ git status
$ git log --oneline -5

Then ask two questions. Is the change committed? And if it is, has it been pushed where others may have pulled it? The answers pick the tool:

SituationTool
Edited a file, not staged, want it back as it wasgit restore <file>
Staged something by mistakegit restore --staged <file>
Last commit has a typo or a missing file, not pushedgit commit --amend
Last few commits are wrong, not pushedgit reset
A commit is already pushed and sharedgit revert
New untracked files to deletegit clean
“I ran something and lost commits”git reflog

git restore: files in the working tree and index

Discard your edits to a file and get the last committed version back:

$ git restore server.js

Unstage a file but keep your edits:

$ echo "DEBUG=true" >> .env.example
$ git add .env.example
$ git restore --staged .env.example
$ git status -s
 M .env.example

Get a file as it was in another commit or branch:

$ git restore --source=HEAD~3 server.js
$ git restore --source=main -- deploy/

Warning: git restore <file> throws away uncommitted edits for good. They were never committed, so not even the reflog can bring them back. Check git diff <file> first.

Fixing the last commit with –amend

Forgot a file or wrote a bad message in the commit you just made?

$ git add search.test.js
$ git commit --amend -m "Add search endpoint with tests"
$ git commit --amend --no-edit          # add staged changes, keep the message

Amend replaces the last commit with a new one (new ID). Fine before you push; after pushing, it rewrites shared history, like a rebase.

git reset: move the branch back

git reset <commit> moves the current branch pointer to another commit. The three modes decide what happens to the changes from the commits you “removed”:

ModeBranch movesStaging areaWorking treeUse it to
--softYesKeeps the changes, stagedUntouchedRedo the commits, e.g. combine them into one
--mixed (default)YesReset, changes unstagedUntouchedUncommit and restage differently
--hardYesResetReset, changes deletedThrow the commits and edits away
$ git log --oneline -3
f1a9e20 (HEAD -> feature/search) Add debug logging
b7d3c11 Add date ranking to search
c42d9e1 Add search endpoint
$ git reset --soft HEAD~2        # undo two commits, keep everything staged
$ git commit -m "Add search with date ranking"
$ git reset --hard HEAD~1        # delete the last commit and its changes
HEAD is now at b7d3c11 Add date ranking to search

Use reset only on commits you have not pushed. Resetting a pushed branch and force-pushing removes commits others may have.

Tip: Before a risky reset, leave a bookmark: git branch backup/before-reset. If anything goes wrong, git reset --hard backup/before-reset puts everything back.

git revert: undo a pushed commit safely

On shared branches, you do not erase history: you add a new commit that does the opposite of the bad one.

$ git log --oneline -3
e3c71b0 (HEAD -> main, origin/main) Enable experimental cache
90bd114 Bump Node.js to 24
5d1e0a2 Add README and API entry point
$ git revert e3c71b0
[main 4a2d9f8] Revert "Enable experimental cache"
 1 file changed, 1 insertion(+), 1 deletion(-)
$ git push

Everybody can pull this normally; nobody’s history breaks, and the log records that the cache was enabled and then reverted. To revert a merge commit, tell Git which parent is the main line: git revert -m 1 <merge-commit>.

git clean: remove untracked files

Build output, generated files or experiments that were never added are not touched by restore or reset. git clean deletes them. Always preview first:

$ git clean -n          # dry run: what would be deleted
Would remove debug.log
Would remove tmp/
$ git clean -fd         # delete untracked files and directories
$ git clean -fdx        # also ignored files such as node_modules (careful)

The reflog: your safety net

Git keeps a log of every position HEAD has been at, called the reflog. It is how you recover “lost” commits after a bad reset, rebase or branch delete:

$ git reset --hard HEAD~3        # oops, those commits were needed
$ git reflog
b7d3c11 HEAD@{0}: reset: moving to HEAD~3
f1a9e20 HEAD@{1}: commit: Add debug logging
...
$ git reset --hard f1a9e20       # back to where you were

Reflog entries are kept for 90 days by default and are local to your machine. They protect commits, not uncommitted edits.

git history: edit commits without a rebase

Git 2.54 introduced an experimental git history command for the most common history edits. Unlike an interactive rebase, it does not need a clean working tree, does not open a todo list and updates every local branch that contains the edited commit. Git 2.55 and 2.56 added more subcommands:

CommandSinceWhat it does
git history reword <commit>2.54Opens the editor to change that commit’s message
git history split <commit>2.54Lets you pick hunks, like git add -p, to carve out into a separate commit
git history fixup <commit>2.55Folds what is staged now into that earlier commit
git history drop <commit>2.56Removes the commit and replays the later ones on its parent
$ git history reword c42d9e1            # fix a typo in an older message
$ git add search.js
$ git history fixup c42d9e1             # put the staged fix into that commit
$ git history drop f1a9e20              # remove the debug logging commit

It refuses to work on history that contains merge commits and stops instead of producing conflicts, so it is safe to try. The same golden rule as rebasing applies: only edit commits you have not shared. Because the command is experimental, its options may still change between releases.

Real-world scenarios

  • Committed .env with a secret, not pushed: git reset --soft HEAD~1, git restore --staged .env, add it to .gitignore, commit again. If it was pushed, rotate the secret first, then revert or clean history.
  • Pushed a commit that breaks production: git revert <commit> and push. Investigate afterwards.
  • Committed on main instead of a branch, not pushed: git branch feature/x (keeps the commits), git reset --hard origin/main, git switch feature/x.
  • Lost a branch after a rebase went wrong: git reflog, find the commit before the rebase, git reset --hard to it.

Quick reference

TaskCommand
Discard edits to a filegit restore <file>
Unstage a filegit restore --staged <file>
File from another commitgit restore --source=<commit> <file>
Fix the last commitgit commit --amend
Uncommit, keep changes stagedgit reset --soft HEAD~1
Uncommit, keep changes unstagedgit reset HEAD~1
Delete commits and changesgit reset --hard <commit>
Undo a pushed commitgit revert <commit>
Preview / delete untracked filesgit clean -n / git clean -fd
Find lost commitsgit reflog
Reword, split, fixup, drop (experimental)git history <subcommand> <commit>

Exercise

You staged config.env by mistake but want to keep your edits in the file. Which command?

  1. git restore –staged config.env
  2. git restore config.env
  3. git reset –hard
  4. git clean -f config.env
Show answer

Answer: A. –staged removes the file from the staging area only, so the edits stay in the working tree. Plain git restore would throw the edits away, and reset –hard would discard every change.

Exercise

A commit that enabled a broken cache was pushed to main an hour ago and teammates have pulled. How do you undo it?

  1. git reset –hard HEAD~1 and git push –force
  2. git commit –amend and push
  3. git history drop <commit>
  4. git revert <commit> and push
Show answer

Answer: D. revert adds a new commit that cancels the bad one, so shared history is not rewritten and everyone can pull normally. reset, amend and history drop all rewrite commits others already have.

Exercise

You ran git reset –hard HEAD~3 and realise you needed those commits. Nothing was pushed. How do you get them back?

  1. They are gone; hard reset cannot be undone
  2. Find the previous position in git reflog and git reset –hard to it
  3. Run git revert HEAD three times
  4. Run git clean -n to list the lost commits
Show answer

Answer: B. The reflog records every position of HEAD, including the one before the reset. Resetting back to that commit restores the branch and its changes. Uncommitted edits, however, would not be recoverable.

Key takeaways

  • Check git status and git log first, and ask: committed? pushed?
  • git restore works on files; --staged unstages, --source brings back older versions.
  • git reset --soft, --mixed and --hard move the branch back and differ in what they keep; use them only on unpushed commits.
  • git revert is the safe undo for shared history; git clean -n previews deleting untracked files.
  • The reflog recovers lost commits, and the experimental git history rewords, splits, fixes and drops commits without a rebase.

FAQ

What is the difference between git reset and git revert?

reset moves your branch back so the commits disappear from it, which rewrites history. revert keeps history and adds a commit that undoes an earlier one. Use reset for local work, revert for anything pushed.

How do I undo the last commit but keep my changes?

git reset --soft HEAD~1 keeps them staged; git reset HEAD~1 keeps them in the working tree but unstaged. Both work only cleanly if the commit was not pushed.

Can I recover changes after git reset –hard?

Committed work, yes, through git reflog, for about 90 days. Edits that were never committed or stashed, no. That is why a quick git stash or a backup branch before risky commands is a good habit.

How do I discard all local changes and match the remote exactly?

git fetch, then git reset --hard origin/main and git clean -fd. This deletes every local commit and change on that branch, so make sure that is what you want.

Should I use git history or git rebase -i?

For one quick change to an older commit (reword, fixup, split or drop), git history is simpler and does not touch your working tree. For reordering, squashing many commits or histories with merges, use interactive rebase. Remember git history is still experimental.

Why did git checkout -m behave differently after I upgraded?

Since Git 2.55, when git checkout -m cannot carry your local changes cleanly to the other branch, it saves them in an automatic stash entry, so they are never left half-merged and lost. Check git stash list if changes seem missing.

↑ ↓ navigate Enter open Esc close