In software development, it’s common to make mistakes or want to revisit a previous state of your project. Git makes it easy to “go back in time” to earlier commits, whether temporarily or permanently. In this guide, you’ll learn how to go to a previous commit in Git using checkout
, reset
, and revert
—and when to use each one.
🎯 Use Case Overview
Goal | Recommended Command |
---|---|
Temporarily browse a previous commit | git checkout <commit> |
Permanently reset project to a commit | git reset |
Undo a commit without losing history | git revert |
🧭 1. Temporarily Switch to a Previous Commit
If you just want to view or test an older commit without changing your branch history:
git checkout <commit-hash>
Example:
git checkout a1b2c3d
This puts you in a “detached HEAD” state—any new commits won’t belong to a branch unless you create one.
✅ To return to the latest commit:
git checkout main
Or your current branch name.
🧹 2. Permanently Go Back to a Previous Commit Using reset
If you want to move your branch back to a previous commit and optionally discard changes:
Soft Reset (keep changes staged):
git reset --soft <commit-hash>
Mixed Reset (unstage changes, but keep files):
git reset <commit-hash>
Hard Reset (delete all changes after the commit):
git reset --hard <commit-hash>
Example:
git reset --hard a1b2c3d
⚠️
--hard
is destructive. Make a backup branch first if unsure:git branch backup-before-reset
♻️ 3. Revert to a Previous Commit Without Changing History
If you’ve already pushed your commits or are working in a shared repo, use revert
:
git revert <commit-hash>
This creates a new commit that undoes the changes from the target commit—without rewriting history.
Ideal for safe, collaborative undoing.
🔍 Find the Commit You Want
To see the history of commits:
git log --oneline
Sample output:
a1b2c3d Add login feature
f4e5d6c Fix typo
789abcd Initial commit
Use the hash (e.g., a1b2c3d
) to reference the desired commit.
🧠 Summary
Task | Command |
---|---|
Temporarily go to a commit | git checkout <commit> |
Go back and keep staged files | git reset --soft <commit> |
Go back and keep working files | git reset <commit> |
Go back and discard everything | git reset --hard <commit> |
Safely undo a commit | git revert <commit> |
View commit history | git log --oneline |
🔐 Pro Tip: Use Branches Before You Reset
Before doing any destructive operations like reset --hard
, always create a backup branch:
git checkout -b safe-copy
That way, you can restore your work if needed.