Git Undoing Changes
Everyone makes mistakes. Git gives you safe ways to undo them, depending on how far the change has gone.
Which Command Should I Use?
| Situation | Command |
|---|---|
| I edited a file and want the last committed version back | git restore file |
| I staged a file by mistake | git restore --staged file |
| My last commit message is wrong, or I forgot a file | git commit --amend |
| I want to undo a commit that is already shared | git revert <commit> |
| I want to remove my last local commits | git reset <commit> |
Discard Changes in a File
You broke index.html and want to go back to the last commit:
Example
git restore index.htmlBe careful: this throws away your uncommitted edits to that file for good. Git cannot bring them back, because they were never committed.
Unstage a File
You ran git add . but did not want to include notes.txt:
Example
git restore --staged notes.txt
git statusOn branch main Changes to be committed: (use "git restore --staged <file>..." to unstage) modified: index.html Untracked files: (use "git add <file>..." to include in what will be committed) notes.txt
The file itself is not changed; it is just taken out of the next commit.
Fix the Last Commit
Forgot a file, or made a typo in the message? If you have not pushed yet:
Example
git add contact.html
git commit --amend -m "Add contact page and form"This replaces the last commit with a new, corrected one.
git revert: The Safe Undo
git revert creates a new commit that does the opposite of an old one. History is kept, so it is safe even after you shared your work on GitHub.
Example
git revert a91c3e7
git log --onelined4e5f60 (HEAD -> main) Revert "Change heading colour to red" a91c3e7 Change heading colour to red 8b41d07 Add basic stylesheet 3f2a9c1 Add home page
Git opens an editor for the message (save and close it to accept). The log then shows a new commit on top that undoes a91c3e7.
git reset: Move Back in History
git reset moves your branch back to an older commit, as if the later commits never happened. It has three modes:
| Mode | Commits removed | Staging area | Your files |
|---|---|---|---|
--soft | Yes | Changes kept staged | Kept |
--mixed (default) | Yes | Changes unstaged | Kept |
--hard | Yes | Cleared | Changes deleted |
Example
# Undo the last commit but keep the changes in your files
git reset HEAD~1Example
# Throw away the last commit AND its changes completely
git reset --hard HEAD~1Only use git reset on commits you have not pushed. If others already have those commits, use git revert instead, or you will cause problems for your team.
Going Back to See an Old Version
To look at the project as it was in an old commit, without changing anything:
Example
git switch --detach 3f2a9c1Look around, then come back to the latest version:
Example
git switch mainExercise
Exercise
You pushed a bad commit to GitHub and your team already pulled it. What is the safest way to undo it?
