Phase 3Local Git

#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:

View changes
$ 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:

Undo changes to a file
$ git restore index.html

If the file is already in the staging area (after a git add), use --staged to remove it from staging without losing the changes:

Remove from staging
$ git restore --staged index.html

git reset -- Undo a commit

To undo the last commit while keeping the changes in your files:

Undo the last commit (keep changes)
$ git reset HEAD~1
Unstaged changes after reset:
M	index.html

To undo the last commit and delete all changes (warning, this is irreversible!):

Undo and delete (dangerous)
$ git reset --hard HEAD~1
HEAD is now at a1b2c3d Initial commit

HEAD~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:

Stash and restore
$ 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:

List stashes
$ git stash list
stash@{0}: WIP on main: a1b2c3d Initial commit

Summary

Summary
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 stashes

Your turn

Try the commands to fix mistakes in the terminal below. Start with git diff to see the changes.

terminal — bash
user@stemlegacy:~/my-project$