Git Reflog Recovery: Find Commits Lost After Reset or Rebase
Recover committed work with Git reflog, inspect the right commit, pin a rescue branch and review it in a separate worktree. Includes an isolated recovery lab.
A commit disappearing from your current branch does not necessarily mean its object was deleted. Git reflog can reveal earlier local reference values after a reset, rebase, or other history movement. The useful recovery sequence is to identify the right commit, verify its contents, and give it a new branch name before changing the current checkout. This guide uses that approach and provides an isolated, executable lab for reset and rebase recovery.
Preserve the repository you still have
Stop making exploratory history changes when you notice missing work. Start with git status and record which branch or detached HEAD you are on. Preserve valuable uncommitted changes and untracked files before any operation that could overwrite them. Reflog is evidence about reference movement; it is not a backup of everything currently visible in your editor.
For important recovery, preserve a copy or snapshot of the repository and working files before cleanup. Include the actual Git storage, not merely the visible source directory. In a linked worktree, the .git entry can point elsewhere, so copying that worktree directory alone may not capture the repository objects and logs you need.
Avoid garbage collection, reflog expiration, pruning, and further resets while investigating. These operations have legitimate maintenance uses, but they are not the first response to missing history. A fresh network clone is also not a substitute for preserving the original local repository: it does not reproduce the sequence of local reference movements that happened here.
Read the log as reference history, not commit ancestry
Run git reflog show HEAD to inspect recent HEAD movements. The HEAD log also includes branch switches, which can make it noisier than the log for a particular branch. If the affected branch still exists, inspect its reflog too. Use messages, dates, branch context, and commit contents together to locate a plausible previous tip.
An expression such as HEAD@{1} identifies a previous value from the local reflog. It does not mean the first parent of the current commit. HEAD~1 follows commit ancestry, while the reflog selector follows recorded reference updates. After a branch switch or several commands, those can identify completely different commits.
Quote selectors containing braces in shell commands. Once you have identified a candidate, resolve and record its full object ID. Reflog positions can shift as later commands add entries. A fixed object ID is a more reliable investigation reference than repeatedly asking what the latest previous value happens to be.
| Expression | Question it answers |
|---|---|
| HEAD~1 | What is the first parent of the current commit? |
| HEAD@{1} | What previous value is recorded in this local HEAD reflog? |
| topic@{1} | What previous value is recorded for the local topic reference? |
| Full commit object ID | Which exact commit object did I select? |
Verify the candidate before restoring anything
Inspect the commit message, parents, changed paths, and the content you actually need. A familiar message alone is weak evidence: an amended or rebased commit can retain the same subject while changing its object ID and surrounding history. Confirm the expected file version and compare the candidate with the current branch.
The commands below use a deliberately obvious placeholder. Replace it with the full commit ID you selected; replace the path with a relevant tracked file. These are inspection commands, so they help establish evidence without moving your current branch. If the object cannot be read, a reflog entry by itself cannot recreate its contents.
For a series of commits, review the range and its relationship to the current history. Recovering an old tip restores access to its reachable history, but it does not automatically decide which of those changes belong in the current branch. Keep identity verification separate from the integration decision.
candidate=PASTE_FULL_COMMIT_ID_HERE
git show --stat --summary "$candidate"
git show "$candidate" -- path/to/file
git diff --stat HEAD "$candidate"Pin a rescue branch, then inspect in another worktree
Create a new branch at the verified commit. Choose an unused name so the command fails rather than overwriting an existing recovery reference. Creating this branch does not check it out or replace your working files. It gives the commit an ordinary reference, so you no longer depend solely on a shifting reflog selector to find it.
Use a separate worktree when you want to open or test the recovered version without disturbing your current checkout. Select a new path that is not already used for valuable files. The worktree shares repository storage but has its own checkout, index, and HEAD. It is an inspection space, not an independent backup of the object database.
After review, decide whether to keep the old line of development, selectively integrate changes, or compare it with rewritten history. Cherry-picking can create new commits and conflicts; switching branches can interact with uncommitted work. Those steps deserve their own review. Recovery does not require immediately resetting your current branch or force-pushing a shared branch.
git branch rescue/recovered "$candidate"
git worktree add ../recovery-review rescue/recovered
git -C ../recovery-review log -5 --oneline
git -C ../recovery-review status --shortSource: Git: worktree inspection and shared repository storage ↗
Distinguish reset recovery from rebase recovery
After a reset, an earlier branch tip can still identify the exact committed snapshot that stopped appearing on the branch. Pinning it to a rescue branch exposes that snapshot again. It does not reconstruct uncommitted edits discarded by a hard reset. Treat saved commits, staged content, and unsaved editor changes as different recovery problems.
After a rebase, the new commits often have different IDs because their parents or other commit data changed. An old tip can therefore be valuable even if the subject lines look familiar. Review the affected branch’s reflog around the completed rebase, then compare the old and new lines before deciding whether anything is actually missing.
ORIG_HEAD can be a useful clue, but it is not a permanent checkpoint. Commands such as reset can replace its value. During a rebase that is still in progress, an abort operation is a different workflow from recovering history after the rebase completed. Read status first so you do not apply advice for the wrong state.
Run two recovery experiments without touching a real project
Save this script as reflog_lab.py and run python reflog_lab.py on a machine with Python 3 and a Git version supporting git init -b and git switch. It creates fresh repositories inside a temporary directory, configures a synthetic author locally, and uses no remote. It intentionally hard-resets only its newly created reset-case repository.
The second experiment creates a topic commit, advances main, and rebases topic. It then recovers the old topic tip into a separate worktree while a tracked draft and an untracked file remain in the original checkout. Assertions check object identity, recovered file content, current HEAD, and the preserved local files. The temporary directory is removed when the script finishes.
The selectors HEAD@{1} and topic@{1} are correct for this controlled command sequence. They are not universal recovery recipes. In a real repository, inspect the actual log and verify the selected ID before creating a branch. The script records expected IDs before each experiment so its assertions can independently detect a wrong selection.
import os
import subprocess
import tempfile
from pathlib import Path
# Ignore inherited repository overrides and global/system Git configuration.
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull,
GIT_TERMINAL_PROMPT="0")
def git(repo, *args):
return subprocess.check_output(
["git", "-c", "core.hooksPath=" + os.devnull,
"-c", "commit.gpgsign=false", "-c", "gc.auto=0", *args],
cwd=repo, env=env, text=True, stderr=subprocess.STDOUT).strip()
def initialize(repo):
repo.mkdir()
git(repo, "init", "-q", "-b", "main")
git(repo, "config", "user.name", "Reflog Lab")
git(repo, "config", "user.email", "lab@example.invalid")
git(repo, "config", "core.logAllRefUpdates", "true")
def commit_file(repo, name, text, message):
(repo / name).write_text(text, encoding="utf-8")
git(repo, "add", "--", name)
git(repo, "commit", "-q", "-m", message)
return git(repo, "rev-parse", "HEAD")
with tempfile.TemporaryDirectory(prefix="reflog-lab-") as directory:
root = Path(directory)
reset_repo = root / "reset-case"
initialize(reset_repo)
base = commit_file(reset_repo, "notes.txt", "base\n", "base")
lost = commit_file(reset_repo, "notes.txt", "saved work\n", "saved work")
# Deliberate destructive operation ONLY in the newly created lab repository.
git(reset_repo, "reset", "--hard", "HEAD~1")
candidate = git(reset_repo, "rev-parse", "HEAD@{1}")
assert candidate == lost
git(reset_repo, "branch", "rescue-reset", candidate)
assert git(reset_repo, "rev-parse", "HEAD") == base
assert git(reset_repo, "show", "rescue-reset:notes.txt") == "saved work"
assert git(reset_repo, "status", "--porcelain") == ""
rebase_repo = root / "rebase-case"
initialize(rebase_repo)
commit_file(rebase_repo, "base.txt", "base\n", "base")
git(rebase_repo, "switch", "-q", "-c", "topic")
old_tip = commit_file(rebase_repo, "feature.txt", "feature\n", "feature")
git(rebase_repo, "switch", "-q", "main")
commit_file(rebase_repo, "upstream.txt", "upstream\n", "upstream")
git(rebase_repo, "switch", "-q", "topic")
git(rebase_repo, "rebase", "main")
new_tip = git(rebase_repo, "rev-parse", "HEAD")
assert new_tip != old_tip
candidate = git(rebase_repo, "rev-parse", "topic@{1}")
assert candidate == old_tip
(rebase_repo / "feature.txt").write_text("local draft\n", encoding="utf-8")
(rebase_repo / "untracked.txt").write_text("keep me\n", encoding="utf-8")
before = git(rebase_repo, "status", "--porcelain")
git(rebase_repo, "branch", "rescue-before-rebase", candidate)
review = root / "review"
git(rebase_repo, "worktree", "add", str(review), "rescue-before-rebase")
assert git(review, "rev-parse", "HEAD") == old_tip
assert (review / "feature.txt").read_text() == "feature\n"
assert git(rebase_repo, "rev-parse", "HEAD") == new_tip
assert git(rebase_repo, "status", "--porcelain") == before
assert (rebase_repo / "feature.txt").read_text() == "local draft\n"
assert (rebase_repo / "untracked.txt").read_text() == "keep me\n"
print("PASS: reset and pre-rebase commits rescued; review worktree isolated.")
print("PASS: current HEAD, tracked draft and untracked file preserved.")
# The entire disposable lab is removed automatically. No remote is used.Local logs and retention set the recovery boundary
Reflogs belong to the local repository. Your colleague’s machine, a CI checkout, and a remote hosting service do not necessarily have the same entries. If this clone never held the missing commit or has already lost its object, another clone or an appropriate backup may be the useful source. Do not assume an ordinary fetch will download an object that no advertised reference reaches.
The documented default expiration periods include ninety days for ordinary reflog entries and thirty days for entries unreachable from the current tip, with configuration able to change them. These are maintenance defaults, not a promised recovery window. Expiring a log entry and deleting an unreachable object are distinct events; object availability also depends on repository maintenance and reachability.
Creating a rescue reference to an existing commit makes its reachable history available under that name, but it cannot resurrect an already missing object. Retain an appropriate backup strategy for important repositories. A successful lab on recent local commits does not establish recoverability after arbitrary cleanup, corruption, or storage failure.
When the first candidate is wrong or unavailable
If a selector resolves to an unexpected branch switch, inspect the named branch reflog and neighboring entries instead of changing the checkout to see what happens. If the commit exists but the desired file version is absent, you may have selected an amended successor, a different tip, or a commit before the change. Use actual file content and parent relationships to refine the search.
If a branch was removed or its own log is unavailable, other local reference logs may still provide clues, but recovery is not guaranteed. Object inspection tools can sometimes find surviving unreferenced objects; they are not a source of objects that have already been deleted. Preserve evidence before attempting broader object-database investigation.
If the missing work was never committed, say so explicitly. Editor history, filesystem snapshots, other working copies, or specialized investigation of surviving staged blobs may be relevant, but the ordinary reflog procedure is not a general undo mechanism for those cases. Avoid presenting a rescued old commit as proof that all recent edits were recovered.
Verify the recovered work before integrating it
The executable lab passed on Git 2.51.1. It recovered the exact reset and pre-rebase commit IDs and checked that reviewing the old topic did not change the current HEAD, tracked draft, or untracked file. These are local repository checks, not tests of remote-host retention, every rebase conflict scenario, or recovery after object deletion.
For your project, run the relevant checks in the recovery worktree and inspect the differences against the intended integration branch. Record the recovered object ID, the rescue branch name, and the evidence that identifies the desired changes. Coordinate before modifying shared history; a local recovery branch is a useful review artifact even when the team ultimately chooses a different integration strategy.
The practical success condition is more specific than seeing an old message in a log: the intended commit is readable, its contents are verified, a stable reference protects access to it, and your current work remains accounted for. Establish those facts before reaching for an operation that rewrites the branch you are trying to repair.
Your next steps
- Reflog selectors follow local reference movement, not parent ancestry.
- Verify a full commit ID and create an unused rescue branch before changing the checkout.
- A separate worktree helps review recovered commits while preserving current local work.
Sources & official resources
Linked resources checked on 2026-10-28. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →