Mastering Git Undo: A Technical Guide to Reset, Revert, and Reflog
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-leaseis a safer alternative to--forcebecause it prevents overwriting remote changes not present locally.git reflogtracks 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
revertis used instead ofresetto avoid breaking other developers’ histories. - Pitfall: Using
git reset --hardon pushed commits followed bygit 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
Mastering SRE Metrics: A Technical Guide to SLIs, SLOs, and Error Budgets
Learn to balance reliability and feature velocity using SLIs, SLOs, and error budgets, including technical strategies for 99.99% uptime and burn rate alerting.
Decentralizing Git: How to Prevent Collaboration Metadata Loss from Vendor Lock-in
Protect your project from account bans and platform outages by moving Git metadata to peer-to-peer networks using Radicle.
Automated Linux Database Backups: A Guide for PostgreSQL and MySQL
Learn to automate PostgreSQL and MySQL backups on Linux using bash scripts, cron jobs, and AWS S3 to prevent data loss from bad deploys.