PUBLIC BETA OFFER

Save 50% off on an Eligible Learning PlanValid for 1-month plan, 3-month plan, 12-month plan · Code LPXBETA50 · Ends Dec 6, 2026

AZ-401: Recovering Selected Git Data Safely

Diagnose accidental Git data loss, preserve unrelated edits and staging state, choose explicit restore sources and paths, and verify recovery without treating reflog as a backup.

Guide

Content version 1.0

AZ-401: Recovering Selected Git Data Safely

AZ-401: Recovering Selected Git Data Safely

Recover an unintended Git change by first identifying which state is wrong: the working file, its staged version, or the reference to an earlier commit. Preserve the current state and unrelated work, select a verified source and the smallest intended destination, then inspect the result. For ordinary tracked files, Git restore can target the working tree, the index, or both. Reflog can help locate an earlier local reference value; it is not a remote backup.

This troubleshooting method addresses accidental recovery, not removal of exposed secrets or coordinated history rewriting. Its examples are illustrative and have not been executed here. Start with AZ-401: Branch Strategies and Git Worktree Boundaries, and check the installed Git version before applying options from the current manuals.

Stop changes and record what must survive

Suppose an illustrative repository contains an accidentally damaged docs/runbook.md and valuable edits in src/service.c. The goal is to recover the runbook while retaining the service edits and the intended staging state. A clean-looking checkout is not the acceptance criterion: unrelated work must still be present.

Pause editors, assistants and other processes that could write during diagnosis. Record the actual repository and checkout directory, current branch or detached HEAD, selected paths, ongoing operations, and the symptom's approximate time. Confirm that you are inspecting the affected checkout, especially when several worktrees exist.

Preserve an independent recovery copy using an approved backup or snapshot method before changing anything. It must cover the relevant working files, untracked material, staging distinctions and repository data needed for recovery. Verify that the saved bytes can be read. A screenshot of a status display does not preserve a file's content, and a commit-only label does not preserve uncommitted work.

For linked worktrees, account for shared repository data as well as each checkout's state. Copying one working directory alone must not be mistaken for a complete independent repository backup. Keep the preservation location outside the paths the recovery action can replace.

Diagnose the layer before choosing a command

Inspect the working-tree view, index view and relevant committed history in your existing Git client. Compare the selected path's current versions rather than guessing from a filename or a remembered branch name. Record both staged and unstaged differences; a file can have valuable changes in each.

Observation Candidate recovery decision
Working file is damaged; the index contains the desired version Recover the working file from that verified index state
File content is correct, but staging is unintended Correct the index while preserving the working file
Desired content belongs to a known earlier commit Inspect that commit and recover only the selected path
The former commit is no longer easy to find through branch history Inspect local reflog for a candidate reference value
No available source contains the required bytes Stop and investigate independent backups or other retained copies

These observations determine what to examine next; they are not permission to overwrite a destination. If a merge is unresolved, or the affected path involves sparse checkout or a submodule, stop before using the ordinary-file examples. Those cases have additional semantics that require a separate, explicit decision.

For the runbook example, write the expected delta before proceeding: which version should replace the damaged file, whether the runbook's index entry should change, and which unrelated files and staging states must remain identical.

Locate and inspect a candidate source

If normal history does not reveal the wanted commit, inspect the local HEAD reference log:

git reflog show HEAD

Reflog records local reference updates; HEAD's log also records branch switching. Treat an entry as a candidate, then inspect its commit and selected file. Do not assume that the previous numeric entry is the desired content. Reference-log positions can change as further operations occur, so record the actual candidate object identifier (OID) once verified.

Reflog entries can expire, and a useful entry does not guarantee that every required object remains available. Another clone or remote is not a guaranteed copy of this repository's local reference log. Reflog also cannot reconstruct file bytes merely because an editor once displayed them. If the desired content was never retained in an available source, preserve the evidence and investigate another recovery source.

A tag can label a verified object when the repository owner wants a named recovery reference. Use a new, agreed label rather than moving an existing release tag:

git tag "$RECOVERY_LABEL" "$SOURCE_OID"

Here, RECOVERY_LABEL must be an unused owner-approved name and SOURCE_OID the actual reviewed commit identifier. A lightweight tag names an object; it does not save current working files or staging state. Signing and verification are separate operations, so a tag name alone establishes neither authenticity nor a complete backup.

Optional inspection in a detached worktree

An owner-authorized detached worktree can make a candidate easier to inspect without replacing the current checkout's files:

git worktree add --detach "$RECOVERY_DIR" "$SOURCE_OID"

Set RECOVERY_DIR to an unused, explicitly checked absolute directory outside the affected checkout. The command examples use pre-set Bash variables; do not paste placeholder values or run them with unset inputs. No example here creates a worktree in this article's production repository.

The extra checkout shares repository data and ordinary references while having its own HEAD and index. It is useful for inspection, not an independent security boundary or recovery backup. Do not run retrieved project scripts merely to inspect a file. If creating it would conflict with another task or an uncertain repository state, use the existing client's source view instead.

Choose the exact restore destination

For restore, --worktree selects working files and --staged selects the index; combining them selects both. --source names the source tree. Without it, the default source is HEAD when restoring the index, otherwise the index.

Use the following as separate choices after preservation and source inspection, not a sequence to run from top to bottom.

To replace only the example working file from a verified commit:

git restore --source="$SOURCE_OID" --worktree -- "docs/runbook.md"

To undo unintended staging relative to HEAD while retaining the working file:

git restore --source=HEAD --staged -- "docs/runbook.md"

If the verified index itself is the intended source for the working file:

git restore --worktree -- "docs/runbook.md"

Only when both destinations should match the selected commit:

git restore --source="$SOURCE_OID" --staged --worktree -- "docs/runbook.md"

A tracked path absent from the source can be removed to match it. Inspect source-path existence first; a successful command can perform an unwanted removal. Keep the path scope narrow and avoid substituting a whole-directory target.

Review the intended change before authorizing it

For the illustrative damaged runbook, compare the chosen source's runbook with the current working and staged versions. Preserve any useful destination-only paragraphs separately before replacement. If only one portion should be recovered, do not apply a whole-file replacement simply because the source is otherwise correct.

The restore manual also supports interactive patch selection. Use it only after understanding the offered source-to-destination changes and preserving current work. An interactive prompt is not a substitute for a known source or a recovery copy. Do not invent a restore --dry-run option.

A useful pre-action record answers four concrete questions:

  • Which exact source object or verified index state contains the desired content?
  • Which tracked path and destination will change?
  • What content or staging information will that destination lose?
  • How will the unrelated files and staging state be compared afterward?

If any answer is unknown, stop. A blanket reset or clean operation is not a shortcut for answering these questions and can exceed this selected-path recovery task.

Verify recovery and preserve failures honestly

After the chosen action, inspect the recovered runbook and the actual differences. Compare its content with the intended source and verify the intended destination separately from the destination that should have remained unchanged.

For example, a worktree-only recovery should not be accepted merely because the file opens. Confirm that the runbook content is correct, the expected index state remains, and src/service.c still contains its valuable edits. For an index-only correction, verify that the working file's bytes did not change. Record actual observations rather than a generic “recovery succeeded” message.

Use these failure distinctions:

Result Investigation
The path is gone after restore Check whether the selected source lacks it; preserve the current evidence before correcting anything
Expected content is missing Recheck the selected object, path and destination against the preservation record
A reflog candidate cannot supply the file Inspect source availability and path history; a reference-log entry is not proof of a recoverable file version
Unrelated content or staging differs Stop further actions and compare the saved state; do not conceal the discrepancy by clearing more changes
Recovery introduced an old incompatible file Reassess the intended behavior with the project owner; byte recovery alone does not establish application correctness

Keep the original damaged version and all retained evidence until the owner confirms the recovery outcome. Do not overwrite the recovery copy with the newly recovered state to make the comparison appear clean.

If an optional inspection worktree was created, remove only that owned checkout after confirming it contains no work that must survive. Use the documented non-forced removal:

git worktree remove "$RECOVERY_DIR"

If removal is refused, investigate and preserve its contents; do not force deletion. Keep an agreed recovery label until its owner authorizes retirement. Finish with a record of the source, affected paths, intended and actual differences, unchanged unrelated work, and any unresolved limitation. Secret exposure or history removal belongs to the separate incident-coordination task.

Authoritative Sources

  • Git restore manual — explicit source/destination options, selected paths, patch mode and absent-source removal.
  • Git reflog manual — local reference updates, HEAD history and expiry limitations.
  • Git worktree manual — detached inspection checkouts, shared repository data and removal.
  • Git tag manual — object labels, lightweight versus annotated tags and separate signing/verification.
0 views