Git & GitHub ยท Chapter 13 of 42

Restoring and Checking Out Files

Sometimes you want to discard changes to a file and go back to the last committed version. Git provides `git restore` (modern) and `git checkout --` (older) for this purpose.

Be careful: restoring a file discards your uncommitted changes permanently. Always check `git status` and `git diff` first to make sure you actually want to lose those edits.

Syntax
git restore <file>
git restore --staged <file>

Discarding working directory changes

Run `git restore filename` to discard uncommitted changes in the working directory and revert the file to its last committed state.

Unstaging a file

If you accidentally staged a file, run `git restore --staged filename` to move it back to unstaged (without losing the changes themselves).

Example 1 (bash)
git restore app.js

Discards uncommitted changes in app.js, restoring it to the last commit.

Example 2 (bash)
git add app.js
git restore --staged app.js

Unstages app.js while keeping the actual edits in the working directory.

Key points

  • git restore discards uncommitted changes to a file.
  • git restore --staged unstages a file without losing edits.
  • The older git checkout -- filename does the same as git restore.
  • Restoring changes is permanent and cannot be undone easily.
๐Ÿ’ก Note: Double check with git status before restoring โ€” there's no undo for discarded uncommitted changes.

๐Ÿ“ Quick Quiz

1. What does git restore filename do?

2. How do you unstage a file without losing its edits?

3. Can discarded changes from git restore be recovered easily?