How to Reset to a Specific Commit in Git: Simple Guide
Use
git reset <commit-hash> to move your current branch to a specific commit. Add --hard to reset files and staging area, or --soft to keep changes staged.Syntax
The basic syntax to reset to a specific commit in Git is:
git reset [--soft | --mixed | --hard] <commit-hash>
Here:
<commit-hash>is the ID of the commit you want to reset to.--softkeeps your changes staged (ready to commit).--mixed(default) keeps changes in your working directory but unstages them.--hardresets your working directory and staging area to match the commit, discarding changes.
bash
git reset [--soft | --mixed | --hard] <commit-hash>
Example
This example shows how to reset your current branch to a specific commit using --hard, which discards all changes after that commit.
bash
git log --oneline # Output: # a1b2c3d Fix typo in README # 9f8e7d6 Add new feature # 123abcd Initial commit git reset --hard 9f8e7d6 # After this, your branch points to commit 9f8e7d6 and files match that state.
Output
HEAD is now at 9f8e7d6 Add new feature
Common Pitfalls
Common mistakes when resetting to a specific commit include:
- Using
--hardwithout saving changes, which causes data loss. - Resetting commits that have been pushed to shared repositories, which can confuse collaborators.
- Not specifying the correct commit hash, leading to unexpected resets.
Always check your commit history with git log --oneline before resetting.
bash
git reset --hard wrongcommit # Wrong commit hash causes error or unexpected reset git reset --soft 9f8e7d6 # Correct way to keep changes staged while moving HEAD
Quick Reference
| Option | Effect |
|---|---|
| --soft | Moves HEAD to commit, keeps changes staged |
| --mixed (default) | Moves HEAD, unstages changes but keeps them in working directory |
| --hard | Moves HEAD and resets staging and working directory, discards changes |
Key Takeaways
Use
git reset <commit-hash> to move your branch to a specific commit.Add
--hard to discard all changes after the commit; use carefully to avoid data loss.Check commit history with
git log --oneline before resetting.Avoid resetting commits already pushed to shared repositories to prevent conflicts.
Choose reset mode (
--soft, --mixed, --hard) based on whether you want to keep changes staged or not.