Restoring a Commit with git checkout
Purpose: Explore old code without deleting anything.
Command:
git checkout <commit-hash>
Key points:
git checkout allows you to view the project as it was at a certain commit.
The changes are temporary for exploration; the commit history remains intact.
To return to the latest commit on your branch:
git checkout main
(or master, depending on branch name)
Use case: You want to examine previous code without affecting current work.
Restoring a Commit with git reset
Purpose: Permanently discard commits and go back in time.
Command:
git reset --hard <commit-hash>
Key points:
Moves HEAD to the specified commit.
Deletes all commits after the specified commit permanently.
Changes in the working directory are updated to match the chosen commit.
Warning: This removes commits; they cannot be recovered easily.
Use case: You want to undo changes entirely and rewrite history.
The command git reset 798927a moves your current branch backward in time to the specific commit 798927a, while leaving your actual code changes intact.
Key Details
Moves the Pointer: Your current branch now points to commit 798927a.
Keeps Your Work: It preserves all modifications made after that commit in your working directory.
Default Mode (--mixed): Because no mode was specified, Git defaults to --mixed. This means the changes from the undone commits are unstaged (removed from the index) but not deleted.
The Trailing Dot (.): If you included the period at the end (git reset 798927a .), it changes the behavior entirely. It copies the files from that specific commit into your staging area without moving the branch pointer at all.
Reverting Changes with git revert
Purpose: Undo a specific commit without deleting history.
Command:
git revert <commit-hash>
Key points:
Creates a new commit that undoes changes of the target commit.
Conflicts may occur if later commits modified the same lines.
Requires manual conflict resolution in such cases.
Use case: You need to undo a past commit but preserve the project history, e.g., in collaborative projects.
Comparison Table: checkout vs reset vs revert
✅ Key Takeaways:
Checkout = temporary exploration
Reset = permanent history rewrite
Revert = safe undo with history preserved