Git

Git Trick: Undo Your Last Commit Without Losing Changes

Made a mistake in your last commit? Use git reset --soft HEAD~1 to undo it while keeping your changes.

May 16, 2026
3 min read

Technologies Discussed

GitCLIWorkflow

The Scenario

You've just committed code but realized: - You forgot to add a file - You made a typo in the commit message - You committed to the wrong branch - You included unwanted changes

Don't panic! Git provides the perfect solution.

The Magic Command

bash
git reset --soft HEAD~1

This command: - Undoes the last commit - Keeps all your changes staged - Preserves your work - Lets you fix and recommit

Breaking It Down

  • **git reset:** Resets the repository
  • **--soft:** Keeps changes in staging area
  • **HEAD~1:** Refers to the commit before HEAD

Step-by-Step Example

bash
# You've just committed
$ git log -1
commit abc123 "Fix typo"

# Realize you need to change something $ git reset --soft HEAD~1

# Your files are now unstaged but unchanged $ git status Changes not staged for commit: modified: file.js

# Fix whatever you need # Then recommit $ git add . $ git commit -m "Fix typo - correct message"

Other Useful Reset Options

  • **git reset --soft:** Keep changes, undo commit
  • **git reset --mixed:** Default, unstage changes
  • **git reset --hard:** Lose everything (careful!)

If You've Already Pushed

If you pushed before realizing the mistake:

bash
# Reset locally
git reset --soft HEAD~1

# Fix and recommit git add . git commit -m "Better message"

# Force push (use carefully!) git push --force-with-lease

Pro Tips

1. **Use --force-with-lease** instead of --force - Safer for collaborative work - Won't overwrite teammates' changes

2. **You can undo multiple commits** - git reset --soft HEAD~3 (last 3 commits)

3. **Check git reflog if things go wrong** - Shows all recent changes - Can recover "lost" commits

Conclusion

The git reset --soft command is your friend. It lets you fix commits without losing work. Master this and you'll be unstoppable!

About the Author

Rajeev Ranjan Sinha is a full-stack engineer with 10+ years of experience building scalable web applications. He specializes in JavaScript/TypeScript, cloud architecture, and system design.

Get more articles like this

Subscribe to my newsletter for in-depth articles, quick tips, and insights on web development.