Mistakes happen. Sometimes, you need to roll back to a previous commit—whether to undo an error, test a stable version, or explore a past state of your project. Git provides several methods to go back to a previous commit, each suited to different use cases.
This guide will walk you through the main options: checkout
, revert
, and reset
.
🧰 Prerequisites
Before making any changes, it’s a good idea to check your current branch and commit history:
git status
git log --oneline
🔁 Option 1: Temporarily View a Previous Commit
If you just want to look at a previous commit without altering your current branch:
git checkout <commit-hash>
📌 Example:
git checkout a1b2c3d
⚠️ This puts your repo in a detached HEAD state. You can view or test files, but you’re not on a named branch.
To return to your branch:
git checkout main # or your current branch name
🧼 Option 2: Undo the Last Commit (Soft Reset)
To remove the last commit but keep your code changes:
git reset --soft HEAD~1
This moves the branch pointer back by one commit, but keeps your staged files.
🧹 Option 3: Completely Reset to a Previous Commit
To permanently go back and discard all changes after a certain commit:
git reset --hard <commit-hash>
📌 Example:
git reset --hard a1b2c3d
⚠️ Dangerous: This erases history and changes. Only use this on local branches, and never on shared/public branches.
↩️ Option 4: Revert a Commit (Safe for Shared Branches)
To safely undo a commit by creating a new one that reverses its changes:
git revert <commit-hash>
This is ideal for public repositories because it preserves history.
📌 Example:
git revert a1b2c3d
Git will launch your default editor to enter a commit message for the revert.
🧠 Which Method Should You Use?
Goal | Command | Safe for Shared Branches? |
---|---|---|
Just view old commit | git checkout <commit> | ✅ |
Undo last commit (keep changes) | git reset --soft HEAD~1 | ❌ |
Completely reset history | git reset --hard <commit> | ❌ |
Safely undo with new commit | git revert <commit> | ✅ |
🔐 Pro Tip: Backup Before Resetting
If you’re unsure, create a backup branch first:
git branch backup-branch
This way, you can always return to the current state before resetting or reverting.
🎯 Final Thoughts
Going back to a previous commit is a powerful way to fix mistakes or explore your project’s history. By understanding the difference between checkout
, reset
, and revert
, you can safely and effectively manage your codebase.