How to Revert to a Previous Git Commit Without Rewriting History
Introduction
1. Identify the Commit to Revert To
Find the commit hash of the desired state using:
git log --oneline
You’ll see something like this:
a1b2c3d Fix critical bug d4e5f6g Add experimental feature h7i8j9k Refactor authentication module j1k2l3m Initial project setup
Suppose you want to revert to commit a1b2c3d
and discard everything after it.
2. Create a New Commit That Matches the Old One
Run the following commands:
git checkout a1b2c3d -- .
git commit -m "Revert to previous stable commit a1b2c3d"
This updates the working directory to match the old commit and creates a new commit reflecting this change.
3. Push the New Commit
If you need to sync the repository, push the new commit:
git push origin main
This avoids force-pushing and keeps a clean history.
Alternative Approach: Using Git Reset (If Force Push is Acceptable)
If rewriting history is an option, you can use:
git reset --hard a1b2c3d
git push --force
Warning: This rewrites history and may cause issues for collaborators.
Conclusion
By checking out a previous commit and creating a new one, you:
- Keep the commit history clean.
- Avoid force-pushing.
- Ensure the latest commit is an exact match of the desired state.
This method is a safer and more collaborative way to revert to an older commit without rewriting history. 🚀
No comments:
Post a Comment