Git by Example: Reset Soft
Learn how to undo commits while keeping your changes staged. This is useful for squashing multiple commits into one or fixing a commit's content entirely.
Code
# 1. Make some commits
git commit -m "WIP: Start feature"
git commit -m "WIP: Continue feature"
# 2. Undo the last 2 commits but keep changes staged
git reset --soft HEAD~2
# 3. Check status
git status
# Output:
# On branch main
# Changes to be committed:
# (use "git restore --staged <file>..." to unstage)
# modified: feature.js
# new file: style.css
# 4. Create a single, clean commit
git commit -m "Add complete feature"Explanation
The git reset --soft command is a safe way to "undo" commits. When you run it, Git moves the HEAD pointer back to a specific commit, but it preserves your work in the staging area (index). This means that all the changes from the undone commits are still there, staged and ready to be committed again.
This command is extremely useful for "squashing" commits. If you have made several small, messy "Work In Progress" (WIP) commits locally, you can use a soft reset to go back to where you started. All your work will be waiting for you in the staging area, allowing you to create a single, polished commit that describes the entire feature.
Think of it as rewinding the timeline but keeping the files exactly as they are now, ready to be saved. It allows you to rewrite the history of how you got to the current state without losing the state itself.
- Moves HEAD pointer back
- Keeps changes in the Staging Area
- Files in working directory are untouched
- Great for squashing commits

