Skip to main content

On This Page

Mastering Git Undo: A Technical Guide to Reset, Revert, and Reflog

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

How to undo commits in Git (locally and on GitHub) and recover “lost” files with reflog

Git provides a comprehensive set of tools for version control recovery. The reflog command serves as a secret history that allows engineers to recover commits even after a destructive reset --hard operation.

Why This Matters

In an ideal development workflow, commits are linear and correct; however, technical reality involves accidental deletions and incorrect pushes. Using --force on shared branches can overwrite remote changes, creating synchronization failures across teams, whereas revert maintains history integrity by creating inverse commits.

Key Insights

  • The difference between history rewriting (reset) and history preservation (revert) determines whether a force push is required.
  • --force-with-lease is a safer alternative to --force because it prevents overwriting remote changes not present locally.
  • git reflog tracks all movements of the HEAD, allowing recovery of ‘lost’ commit hashes (e.g., 3bfb189).
  • git restore --source <COMMIT> -- <FILE> enables surgical recovery of specific files without reverting the entire branch state.

Working Examples

Deletes the last two commits and discards all associated changes.

git reset --hard HEAD~2

Creates new commits that undo previous changes, safe for shared/protected branches.

git revert --no-edit HEAD~2..HEAD
git push origin YOUR_BRANCH

Locates a lost commit hash via reflog and restores the repository state to that hash.

git reflog
git reset --hard 3bfb189

Restores a specific file from a previous commit hash into the current working directory.

git restore --source 3bfb189 -- .gitignore
git add .gitignore
git commit -m "chore: restore .gitignore"
git push origin master

Practical Applications

  • 。Use case: Shared team branches where revert is used instead of reset to avoid breaking other developers’ histories.
  • Pitfall: Using git reset --hard on pushed commits followed by git push --force, which can overwrite colleague’s work.

References:

Continue reading

Next article

Automating OpenAPI Validation with Spectral and SARIF in GitHub Actions

Related Content