Undoing Changes and Errors
It happens to all of us: we save a change that broke everything, accidentally delete a file, or send a commit with an embarrassing typo. Git shines precisely by solving these disasters.
1. Discard unsaved changes (Before Add)
You are writing code, you regret everything you did in the last hour, and you want the file to be exactly the same as in your last official commit.
To discard changes to a specific file:
git restore ruined-file.js
To discard ALL unsaved changes in the project (Danger!):
git restore .
Warning: Whatever you restore here is lost forever. Git had not yet saved it in the history.
2. Remove files from Staging Area (After Add)
You did git add . but you realized you included password files or temporary files that you don't want to dirty the next commit with.
To remove a file from the green "waiting" zone (Staging):
git restore --staged secret-file.env
This does NOT delete the contents of your file. It simply removes it from the "to save" list and returns it to red.
3. Modify the last Commit (After Commit)
You did git commit -m "Add login" but you realized you forgot to add an image, or that the message had a spelling error.
Instead of making a new commit saying "Add the login photo I forgot", you can magically modify the previous one.
- Add the files you forgot (if any):
git add my-image.png - Run the amend command:
git commit --amend -m "Add completed login screen with image"
This overwrites and replaces the last commit in your history.
Golden Rule: NEVER use
--amendon commits you've already sent (pushed) to GitHub. Only amend commits that still live 100% on your local computer.
4. Travel back in time permanently (Hard Reset)
You made 3 commits that are a total disaster and you want your project to go back in time, deleting those commits from the general history of humanity's existence as if they never happened.
# Move your branch back 3 commits and DELETE that code
git reset --hard HEAD~3
Danger:
reset --harddeletes your recent work.
5. Revert politely (Revert)
If your project is already uploaded to GitHub, being shared with your team, you cannot use reset --hard. Deleting part of the shared history will break the project for the rest of the team the next time they pull.
Instead of erasing the error from history, we create a new commit that does exactly the inverse of the error (if you added a word, the revert subtracts it).
# Revert a specific commit using its ID (the alphanumeric "license plate")
git revert 8a4c1b9
This will leave a record in the history that you messed up, but it will also leave a record that you responsibly fixed it by undoing the official changes.