How to Go to a Previous Commit in Git: Checkout, Reset, and Revert Explained

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

GoalRecommended Command
Temporarily browse a previous commitgit checkout <commit>
Permanently reset project to a commitgit reset
Undo a commit without losing historygit 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

TaskCommand
Temporarily go to a commitgit checkout <commit>
Go back and keep staged filesgit reset --soft <commit>
Go back and keep working filesgit reset <commit>
Go back and discard everythinggit reset --hard <commit>
Safely undo a commitgit revert <commit>
View commit historygit 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.

Sharing Is Caring:

Leave a Comment