0
0
GitHow-ToBeginner · 3 min read

How to Undo a Git Commit but Keep Your Changes

Use git reset --soft HEAD~1 to undo the last commit but keep your changes staged. Alternatively, use git reset HEAD~1 to undo the commit and unstage the changes, keeping them in your working directory.
📐

Syntax

The command git reset is used to undo commits in Git. The key parts are:

  • --soft: Moves the HEAD pointer to the previous commit but keeps changes staged.
  • HEAD~1: Refers to the commit before the current HEAD (last commit).

Without --soft, git reset defaults to --mixed, which unstages changes but keeps them in your working directory.

bash
git reset --soft HEAD~1
💻

Example

This example shows how to undo the last commit but keep your changes staged for a new commit.

bash
echo "Hello World" > file.txt

# Stage and commit the file
 git add file.txt
 git commit -m "Add greeting"

# Undo the last commit but keep changes staged
 git reset --soft HEAD~1

# Check status
 git status
Output
On branch main Changes to be committed: (use "git restore --staged <file>..." to unstage) new file: file.txt
⚠️

Common Pitfalls

Common mistakes when undoing commits but keeping changes include:

  • Using git reset --hard HEAD~1 which deletes changes permanently.
  • Confusing --soft and --mixed resets and losing track of staged vs unstaged changes.
  • Trying to undo commits multiple steps back without specifying the correct commit reference.

Always double-check your command before running to avoid losing work.

bash
git reset --hard HEAD~1  # WRONG: This deletes your changes

git reset --soft HEAD~1  # RIGHT: Undo commit but keep changes staged
📊

Quick Reference

CommandEffect
git reset --soft HEAD~1Undo last commit, keep changes staged
git reset HEAD~1Undo last commit, unstage changes but keep them in working directory
git reset --hard HEAD~1Undo last commit and delete changes (dangerous)

Key Takeaways

Use git reset --soft HEAD~1 to undo the last commit and keep changes staged.
Use git reset HEAD~1 to undo the commit and unstage changes but keep them in your files.
Avoid git reset --hard unless you want to delete changes permanently.
Always verify which commit you are resetting to avoid losing work.
Understand the difference between staged and unstaged changes when undoing commits.