Learn GitHub
$ gh ghadvancedgit.ghrecovery

Git History, Undoing Changes, and Recovery

6 learning objectives · 10 key terms · 9 commands · 3 diagrams · 5 quiz questions

$objectives

Git History, Undoing Changes, and Recovery

Advanced Git

Module 3 of 5 · lesson 8 in this module

What you'll be able to do

  • Read commit history at any level of detail, including one specific commit
  • Undo a change safely with git revert on a shared branch
  • Choose between git reset --soft, --mixed and --hard, and explain what each destroys
  • Restore a single file or an accidentally discarded change
  • Use the reflog to recover commits and deleted branches
  • Stash work-in-progress and bring it back without losing it
$concept

The idea, in plain language

Nothing in Git is truly gone until it is unreachable and garbage-collected, which is why Git is very hard to lose work in — and why the right answer to "I broke it" is almost never "delete the repository". Almost every recovery starts by finding the commit you want to return to. git log shows reachable history, git show opens one commit, and git reflog shows every position HEAD has occupied on your machine, including the commits you reset away or the branch you deleted. Reflog entries normally last 90 days, so a lost branch is usually a one-command recovery.

Undoing splits into two families that people constantly confuse. Reverting adds new history: git revert creates a commit that reverses an earlier one, so anyone who already has the original commit stays consistent. Resetting moves history: git reset rewrites where your branch points, so anyone who already has the old commits will diverge. That distinction is the rule — on a branch other people have, revert. On a local branch only you have, reset is fine and often tidier.

The three modes of reset differ only in how much they leave alone. --soft moves the branch pointer and changes nothing else, so the undone changes sit in the staging area ready to re-commit. --mixed (the default) moves the pointer and unstages, leaving changes in your working directory for you to reshape. --hard moves the pointer and throws away both the staging area and the working directory changes for the affected paths. Only --hard destroys work, and only uncommitted work is genuinely at risk.

$key terms

Key terms

git revert
Creates a new commit that undoes a previous one — safe on shared branches.
git reset
Moves your branch pointer backwards; only affects your local branch — unsafe on shared branches.
Soft reset
--soft: move the pointer, keep the changes staged.
Mixed reset
--mixed (default): move the pointer, unstage, keep the changes in your working directory.
Hard reset
--hard: move the pointer and discard staged and working-directory changes. Destructive.
git restore
The modern command for discarding changes to a file or unstaging them.
Reflog
A local log of every position HEAD and branches have held — the recovery tool of last resort.
Stash
A saved pile of uncommitted changes set aside so you can switch branches or pull safely.
Detached HEAD
HEAD pointing directly at a commit; work committed there is not on any branch.
Cherry-pick
Copy one specific commit onto the current branch as a new commit.
$steps

How it works, step by step

  1. 1
    Find the commit you want to undo or return to

    git log --oneline plus git show for the detail. Copy the short hash — every recovery command needs it.

    locatebash
    git log --oneline -10
    git show 8c1d2ab
  2. 2
    If the branch is shared, revert

    git revert adds a commit that reverses the target. History is preserved, everyone who already pulled stays consistent, and the reason is in the log.

    safe on shared branchesbash
    git revert 8c1d2ab
  3. 3
    If the branch is local only, reset

    Choose the mode by what should survive. --soft keeps changes staged, --mixed keeps them unstaged, --hard discards them. Read the command before you run it.

    local branches onlybash
    git reset --soft HEAD~1    # undo the commit, keep changes staged
    git reset --mixed HEAD~1   # undo the commit, unstage, keep changes in files
    git reset --hard HEAD~1    # undo the commit AND discard the changes
  4. 4
    Discard or restore individual files

    git restore is the precise tool: unstage a file, or throw away its working-directory changes. Restoring a file from an older commit is a read from that commit into your working directory.

    filesbash
    git restore --staged config.py        # unstage, keep the edit
    git restore config.py                 # discard the edit
    git restore --source=8c1d2ab config.py  # bring back the old version of one file
  5. 5
    When you have lost something, read the reflog

    Every commit your HEAD pointed at in the last ~90 days is listed, including ones removed by reset. Recover by creating a branch at the hash.

    recoverybash
    git reflog
    # 8c1d2ab HEAD@{3}: reset: moving to HEAD~1
    git switch -c rescue 8c1d2ab
  6. 6
    Set work aside with stash instead of committing junk

    Stash when you must switch context mid-change. Bring it back with pop (apply and drop) or apply (apply and keep). Untracked files need -u; several stashes form a stack you can list and inspect.

    context switchingbash
    git stash push -u -m "half-finished login form"
    git stash list
    git stash pop
    git stash apply stash@{0}
$commands

Commands worth memorising

Every block below is copy-ready — use the Copy button, then paste it into your terminal. Expected output is shown underneath so you know what “working” looks like.

undo on a shared branchbash
git revert 8c1d2ab
Output
[main 1f2e3d4] Revert "Extend session timeout"
 1 file changed, 3 insertions(+), 3 deletions(-)

Safe because it adds history rather than rewriting it. Everyone who already pulled the original commit stays consistent.

uncommit, keep everything stagedbash
git reset --soft HEAD~1
Output
Unstaged changes after reset:
M	config.py

HEAD~1 means "one commit before HEAD". The commit is gone from the branch but its content is staged, ready to re-commit differently.

uncommit and unstagebash
git reset --mixed HEAD~1

The default mode. Changes remain in your working directory; git status will list them as modified.

throw the commit and its changes awaybash
git reset --hard HEAD~1
Output
HEAD is now at 3f9a1c2 Add deployment notes

Destructive. Recoverable via git reflog while the commit is still listed there, but only for committed content.

see every position HEAD heldbash
git reflog --date=relative
Output
8c1d2ab HEAD@{2 minutes ago}: commit: Extend session timeout
3f9a1c2 HEAD@{1 hour ago}: reset: moving to HEAD~1
9a7b6c5 HEAD@{yesterday}: commit: Add login form

Includes commits that are no longer on any branch — exactly what you need after a bad reset or a deleted branch.

recover a deleted branchbash
git branch rescue 9a7b6c5

Find the hash in the reflog, then create a branch pointing at it. Nothing was truly deleted until garbage collection ran.

stash work in progressbash
git stash push -u -m "wip: login form"
Output
Saved working directory and index state On main: wip: login form

-u also stashes untracked files, which are otherwise left behind and can block a branch switch.

bring it backbash
git stash pop
Output
On branch main
Changes not staged for commit:
  modified:   login.js
Dropped refs/stash@{0} (1a2b3c4)

pop applies the newest stash and removes it from the stack. Use git stash apply to keep a copy.

copy one commit to another branchbash
git cherry-pick 4f1c2ab
Output
[hotfix 8c1d2ab] Fix null pointer in export
 Date: Mon Mar 4 10:12:07 2026 +0000

Creates a new commit with the same change on the current branch. Useful for pulling a fix into a release branch.

$diagrams

Workflow diagrams

Diagram 1Revert adds history; reset rewrites it

This one distinction decides which command is safe when other people have your branch.

Reading the diagram
  1. Revert appends a commit that reverses the target, so anyone who already has the original stays consistent.
  2. Reset moves the branch pointer, so anyone who has the old commits will diverge — fine on your own branch, disruptive on a shared one.
  3. Rule of thumb: if you have pushed and someone else may have pulled, revert.
Diagram 2The three reset modes

Only --hard destroys anything, and only uncommitted work is at real risk.

Reading the diagram
  1. --soft is for re-shaping the last commit: keep the content, change the message or split it.
  2. --mixed is for "uncommit and start over on the files".
  3. --hard is for discarding work you are certain you do not want.
Diagram 3The reflog is your undo history

HEAD has pointed at many places; the reflog remembers all of them for about 90 days.

Reading the diagram
  1. Resetting or deleting a branch does not delete the commits — it only removes the reference.
  2. git reflog lists every commit HEAD has pointed at, newest first, including unreachable ones.
  3. Create a branch at the hash you want back and your work is on a branch again.
$example

Worked example

A bad reset, discovered and fully reversed. This is the scenario people dread; it takes three commands.

recovering from a hard resetbash
git log --oneline
# 8c1d2ab (HEAD -> main) Extend session timeout
# 3f9a1c2 Add deployment notes

# mistake: meant --soft, typed --hard
git reset --hard HEAD~1
# HEAD is now at 3f9a1c2 Add deployment notes
git status
# nothing to commit, working tree clean      <- work appears gone

git reflog
# 3f9a1c2 HEAD@{0}: reset: moving to HEAD~1
# 8c1d2ab HEAD@{1}: commit: Extend session timeout
# 3f9a1c2 HEAD@{2}: commit: Add deployment notes

git branch rescue 8c1d2ab
git log --oneline --all
# 8c1d2ab (rescue) Extend session timeout
# 3f9a1c2 (HEAD -> main) Add deployment notes

# put it back on main properly
git switch main
git merge rescue
git branch -d rescue
git log --oneline
# 8c1d2ab (HEAD -> main) Extend session timeout
# 3f9a1c2 Add deployment notes
Output
The "lost" commit is back on main, and nothing was ever actually deleted.
1The hard reset moves main back one commit. git status shows a clean tree, which is what makes this feel catastrophic — the commit is off the branch, not deleted.
2git reflog lists every position HEAD has occupied. The second line is the commit we just removed, with its hash 8c1d2ab.
3git branch rescue 8c1d2ab creates a new branch at that commit. Once a branch points at it, the commit is reachable and safe from garbage collection.
4git log --all shows both branches so you can confirm the commit content survived intact.
5Fast-forwarding main onto rescue restores the original state exactly, and deleting the temporary branch leaves no trace of the recovery.
$use cases

Where you'll use it

▸Rolling back a deployed change that broke production without rewriting shared history.
▸Splitting an over-large commit into three smaller ones with a soft reset.
▸Recovering a branch deleted after an unfinished feature was accidentally merged.
▸Unstaging a file that should never have been included in the commit.
▸Setting aside half-finished work to fix an urgent bug on main, then resuming.
▸Bringing a one-line fix from main into a maintenance branch with cherry-pick.
$mistakes

Common mistakes

  • Using git reset on a branch other people have pulled, then force-pushing and breaking everyone else’s history.
  • Running git reset --hard without checking git status first, destroying uncommitted work that was never committed anywhere.
  • Believing a reset deleted the commit — the reflog almost always still has it.
  • Force-pushing after a reset to a shared branch instead of reverting.
  • Stashing on the wrong branch and popping it somewhere unexpected.
  • Running git clean -fdx in a project folder without realising it deletes untracked files and ignored directories permanently.
$best practices

Best practices

  • On any shared branch, undo with git revert. Reserve git reset for branches only you have.
  • Check git status before any destructive command — uncommitted work is the only thing that is genuinely fragile.
  • Use git restore to discard a single file rather than resetting a whole branch.
  • Remember git reflog as the first step of every "I lost my work" recovery.
  • Stash with a message (-m) and, when untracked files are involved, with -u.
  • Never force-push a shared branch; if you must rewrite your own feature branch, use --force-with-lease.
$exercise

Hands-on exercise

Break your repository on purpose, then fix it three ways

Make mistakes in a practice repository so the recovery paths are muscle memory.

  1. Make three commits on a branch. Then run git reset --hard HEAD~1 and confirm with git status that the newest commit looks gone.
  2. Recover it using git reflog and git branch, then merge the recovery branch back and delete it.
  3. Make another commit, then undo it with git revert and read the resulting commit message.
  4. Make a change to a file, stage it, then run git restore --staged on it and describe in one sentence where the change went.
  5. Start editing a file, run git stash push -m "wip", switch branches, switch back, and run git stash pop. Confirm the edit returned.
  6. Run git log --oneline --graph and identify which of your operations added history and which rewrote it.

💡 Hint: The reflog is per-repository and local — it exists on your machine only, and entries expire after roughly 90 days, so recover promptly.

Done when: You have recovered a hard-reset commit, reverted a shared-branch commit, and popped a stash without losing any work.

$quiz

Checkpoint quiz

0 of 5 answered · 0 correct

  1. Multiple choiceQ1

    A commit was pushed to main yesterday and broke production. Which command should you use, and why?

  2. Command outputQ2

    You ran git reset --soft HEAD~1. Where did the commit’s changes go?

  3. TroubleshootingQ3

    You deleted a branch with git branch -D and the commits were not merged. Which command finds them?

  4. True or falseQ4

    True or false: git reset --hard can destroy work that was never committed anywhere.

  5. Multiple choiceQ5

    What is the difference between git stash pop and git stash apply?

$summary

Module summary

  • Revert adds history and is safe on shared branches; reset rewrites your local branch only.
  • --soft keeps changes staged, --mixed keeps them unstaged, --hard discards them.
  • git restore is the precise tool for unstaging or discarding a single file.
  • The reflog lists every commit HEAD has pointed at for around 90 days — the first place to look when work seems lost.
  • Stash with a message and -u so untracked files come along; pop applies and drops, apply keeps.
  • Cherry-pick copies one commit onto the current branch, which is how a fix reaches a release branch.

Next up: Recovery assumes something went wrong. Module 9 changes the subject to designing workflows so less goes wrong: Git Flow, trunk-based development, rebasing, tags and releases.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Put the GitHub course to work: open one of the company-wise repositories and follow the workflow you just learned, branch to release.