Undoing Mistakes in Git – A Guide to Reverting Changes

Why Undoing Mistakes is Important?

Mistakes happen! Whether you staged the wrong file, committed the wrong changes, or pushed something by accident, Git provides powerful commands to undo and revert changes safely.

This guide will help you learn how to:

✅ Unstage files from the staging area.
✅ Undo commits without losing work.
✅ Revert pushed commits.
✅ Recover deleted files.


Checking Your Current Status

Before undoing anything, check the current state of your repository:

git status

This command helps you determine if changes are:

  • Unstaged (modified but not staged)
  • Staged (added to the index but not committed)
  • Committed (saved in history but not pushed)

Unstaging Files (Removing from Staging Area)

If you staged a file but haven’t committed yet, remove it from the staging area:

git restore --staged <file-name>

Example:

git restore --staged index.html

This keeps your changes but removes the file from staging.

To unstage all files:

git reset

⏪ Undoing the Last Commit (Without Losing Changes)

If you committed too soon but haven’t pushed, you can undo the last commit while keeping changes:

git reset --soft HEAD~1

This moves the changes back to the staging area.

To undo the last commit and move changes to the working directory:

git reset --mixed HEAD~1

If you want to completely discard the last commit and all changes:

git reset --hard HEAD~1

Be careful! --hard deletes changes permanently.


Reverting a Commit (Safe Way to Undo Changes)

If a commit has already been pushed, use git revert to create a new commit that undoes the previous one:

git revert <commit-hash>

Example:

git revert 1a2b3c4d

This keeps history intact and is safer for shared repositories.

To find commit hashes:

git log --oneline

Deleting Uncommitted Changes (Discard Changes in a File)

To discard local changes in a specific file:

git restore <file-name>

Example:

git restore styles.css

To discard all uncommitted changes:

git restore .

To discard all uncommitted changes using the older git checkout command:

git checkout .

Note: git checkout . is an older command and has been replaced by git restore ., but it still works in many cases.

This cannot be undone, so use with caution!


Recovering Deleted Files

If you deleted a file and need to restore it before committing:

git checkout -- <file-name>

If already committed, restore it from history:

git checkout HEAD~1 -- <file-name>

Next Steps

Now that you know how to undo mistakes in Git, explore more topics:

Pushing & Pulling from GitHub & GitLab – Learn how to sync your local repository with remote repositories.
Git Best Practices – Keep your commit history clean and structured.

Need help? Check the official Git documentation or ask in the comments!