#12 Fixing mistakes
diff, restore, reset, stash
git diff -- View changes
Before saving anything, it is useful to see exactly what has changed. The git diff command displays the differences between your current files and the last commit:
$ git diff
diff --git a/index.html b/index.html
--- a/index.html
+++ b/index.html
@@ -1,3 +1,4 @@
<html>
+ <h1>Hello</h1>
<body>
</body>Lines starting with + are additions, those with - are deletions.
git restore -- Undo changes
If you have modified a file and want to go back to its version from the last commit:
$ git restore index.htmlIf the file is already in the staging area (after a git add), use --staged to remove it from staging without losing the changes:
$ git restore --staged index.htmlgit reset -- Undo a commit
To undo the last commit while keeping the changes in your files:
$ git reset HEAD~1
Unstaged changes after reset:
M index.htmlTo undo the last commit and delete all changes (warning, this is irreversible!):
$ git reset --hard HEAD~1
HEAD is now at a1b2c3d Initial commitHEAD~1 means "one commit before HEAD". You can use HEAD~2, HEAD~3, etc. to go further back.
git stash -- Set aside temporarily
Sometimes you are working on something but need to switch branches urgently. git stash sets your changes aside temporarily:
$ git stash
Saved working directory and index state WIP on main: a1b2c3d Initial commit
# ... do something else, switch branches ...
$ git stash pop
On branch main
Changes not staged for commit:
modified: index.html
Dropped refs/stash@{0}You can see the list of saved stashes with git stash list:
$ git stash list
stash@{0}: WIP on main: a1b2c3d Initial commitSummary
git diff # View changes
git restore file.txt # Undo changes
git restore --staged file.txt # Remove from staging
git reset HEAD~1 # Undo commit (keep changes)
git reset --hard HEAD~1 # Undo commit (delete everything)
git stash # Set aside
git stash pop # Restore stash
git stash list # List stashesYour turn
Try the commands to fix mistakes in the terminal below. Start with git diff to see the changes.