Loading

Quipoin Menu

Learn • Practice • Grow

git / Undoing Changes
tutorial

Undoing Changes

Mistakes happen. Git gives you several ways to undo changes depending on whether the change is uncommitted, staged, or already committed.

Undoing Unstaged Changes (Working Directory)

If you modified a file but haven’t staged it yet, you can discard the changes and revert to the last committed version:
git restore file.txt
Or using the older git checkout syntax:
git checkout -- file.txt

Undoing Staged Changes (Unstage)

If you added a file to staging but want to unstage it (keep the changes in working directory):
git restore --staged file.txt
This removes the file from staging but leaves the modifications.

Undoing the Last Commit (Keep Changes)

If you just committed but forgot to include a file or made a mistake in the message, you can undo the commit while keeping the changes staged:
git reset --soft HEAD~1
HEAD~1 means one commit before HEAD. The --soft flag keeps your changes staged.

Undoing the Last Commit (Discard Changes)

To completely discard the last commit and all its changes (dangerous):
git reset --hard HEAD~1
This removes the commit and all changes. Use with caution.

A Safer Way: Revert

Instead of rewriting history with reset, you can create a new commit that undoes the changes of a previous commit. This is safer for shared branches.
git revert HEAD
We’ll cover revert in detail in the next chapter.


Two Minute Drill
  • Discard unstaged changes: git restore file.txt or git checkout -- file.txt.
  • Unstage a file: git restore --staged file.txt.
  • Undo last commit but keep changes staged: git reset --soft HEAD~1.
  • Completely discard last commit and changes: git reset --hard HEAD~1 (dangerous).
  • For shared branches, use git revert instead of reset.

Need more clarification?

Drop us an email at career@quipoinfotech.com