Bird
Raised Fist0
Gitdevops~15 mins

git restore to discard working changes - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - git restore to discard working changes
What is it?
git restore is a command used to undo changes in your working directory. It lets you discard edits you made to files, returning them to the last saved state in your repository. This helps you fix mistakes or start fresh without affecting your commit history. It is a safer and clearer way to undo changes compared to older commands.
Why it matters
Without git restore, undoing changes could be confusing or risky, leading to lost work or messy histories. This command solves the problem of safely discarding unwanted edits, making it easier to manage your code and avoid errors. It helps developers feel confident experimenting, knowing they can quickly revert mistakes.
Where it fits
Before learning git restore, you should understand basic git concepts like the working directory, staging area, and commits. After mastering git restore, you can explore more advanced undo commands like git reset and git checkout for different undo scenarios.
Mental Model
Core Idea
git restore resets files in your working folder back to their last committed state, discarding any unsaved changes.
Think of it like...
Imagine you are writing on a whiteboard and make some marks you don't like. Using git restore is like wiping the whiteboard clean to how it looked before you started writing.
Working Directory
  ┌───────────────┐
  │ Modified File │
  └──────┬────────┘
         │ git restore
         ▼
  ┌───────────────┐
  │ Clean File    │
  └───────────────┘

This shows how git restore changes a modified file back to clean.
Build-Up - 7 Steps
1
FoundationUnderstanding Working Directory Changes
🤔
Concept: Learn what it means when files are changed but not saved in git.
When you edit a file in your project, git sees it as 'modified' but not yet saved in a commit. These changes live only in your working directory until you save them by committing.
Result
You know that changes exist but are not permanent until committed.
Understanding the working directory is key to knowing what git restore will affect.
2
FoundationDifference Between Staged and Unstaged Changes
🤔
Concept: Distinguish between changes you have marked for commit (staged) and those you haven't (unstaged).
Git tracks changes in two places: the staging area (ready to commit) and the working directory (not yet staged). git restore primarily affects unstaged changes unless told otherwise.
Result
You can identify where your changes live and how git restore targets them.
Knowing this helps prevent accidentally discarding changes you meant to keep.
3
IntermediateUsing git restore to Discard Unstaged Changes
🤔Before reading on: do you think git restore affects staged changes by default? Commit to yes or no.
Concept: Learn the basic command to discard changes in files that are not staged.
Run 'git restore ' to reset the file to the last committed version, removing any edits you made but did not stage.
Result
The file returns to its clean, committed state, and your edits are lost.
Understanding this command lets you safely undo mistakes before staging.
4
IntermediateDiscarding Changes in Multiple Files
🤔Before reading on: can git restore discard changes in multiple files at once? Commit to yes or no.
Concept: You can restore multiple files or all files in one command.
Use 'git restore .' to discard all unstaged changes in the current directory and its subdirectories. Or list multiple files separated by spaces.
Result
All specified files revert to their last committed state.
This saves time when you want to discard many changes quickly.
5
IntermediateRestoring Staged Changes with git restore --staged
🤔Before reading on: does git restore remove changes from the staging area? Commit to yes or no.
Concept: Learn how to unstage files using git restore.
Run 'git restore --staged ' to remove a file from the staging area but keep your edits in the working directory.
Result
The file is no longer staged for commit but your changes remain.
Knowing this helps you fix staging mistakes without losing work.
6
AdvancedCombining --staged and Working Directory Restore
🤔Before reading on: can git restore remove changes both from staging and working directory in one command? Commit to yes or no.
Concept: You can discard changes both from staging and working directory together.
Run 'git restore --staged ' to unstage, then 'git restore ' to discard working changes. Or combine with scripting for batch operations.
Result
The file returns to the last commit state with no staged or unstaged changes.
Understanding this combination prevents partial undo mistakes.
7
ExpertWhy git restore Replaced git checkout for This Use
🤔Before reading on: do you think git checkout and git restore do the same thing? Commit to yes or no.
Concept: Learn the design reasons behind introducing git restore as a clearer alternative.
Git checkout was overloaded with many functions, causing confusion and mistakes. git restore was created to separate concerns: restoring files only affects working directory and staging, making commands safer and clearer.
Result
You understand why modern git uses git restore for discarding changes and git checkout for switching branches.
Knowing this history helps avoid confusion and use git commands correctly.
Under the Hood
git restore works by replacing the content of files in your working directory with the content from the last commit or the index (staging area). It reads the saved snapshot and overwrites your current files, effectively discarding any unsaved edits. When using --staged, it updates the staging area by removing the file from the index, but leaves the working directory untouched unless combined with other options.
Why designed this way?
Git originally used git checkout for many tasks, which was confusing and error-prone. To improve clarity and safety, git restore was introduced to focus solely on restoring file content, separating concerns and reducing accidental data loss. This design makes commands more intuitive and easier to learn.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Last Commit   │──────▶│ Staging Area  │──────▶│ Working Dir   │
└───────────────┘       └───────────────┘       └───────────────┘
       ▲                      ▲                      ▲
       │                      │                      │
       │                      │                      │
       │                      │                      │
       └──── git restore <file> ─────────────────────┘

This shows git restore replacing files in working directory from commit or staging.
Myth Busters - 4 Common Misconceptions
Quick: Does git restore delete committed files? Commit yes or no.
Common Belief:git restore can delete files from the repository permanently.
Tap to reveal reality
Reality:git restore only affects your working directory and staging area; it never deletes committed files from the repository history.
Why it matters:Believing this can cause unnecessary fear or misuse, preventing safe undoing of local changes.
Quick: Does git restore affect staged changes by default? Commit yes or no.
Common Belief:git restore discards both staged and unstaged changes by default.
Tap to reveal reality
Reality:By default, git restore only discards unstaged changes; staged changes remain unless --staged is used.
Why it matters:Misunderstanding this can lead to unexpected loss or retention of changes.
Quick: Is git restore the same as git reset? Commit yes or no.
Common Belief:git restore and git reset do the same thing and can be used interchangeably.
Tap to reveal reality
Reality:git restore focuses on working directory and staging area file content, while git reset changes commit history and staging area pointers.
Why it matters:Confusing these commands can cause serious repository state problems or data loss.
Quick: Can git restore recover deleted files from commits? Commit yes or no.
Common Belief:git restore can recover files deleted in previous commits automatically.
Tap to reveal reality
Reality:git restore only restores files to the last commit state in your current branch; it cannot recover files deleted in past commits without extra commands.
Why it matters:Expecting automatic recovery can lead to lost work if proper recovery steps are not taken.
Expert Zone
1
git restore does not update the HEAD or commit history, so it is safe for local undo without affecting others.
2
Using git restore with --source allows restoring files from any commit, not just the latest, enabling selective rollback.
3
git restore can be combined with pathspecs to target specific files or directories precisely, avoiding broad unintended changes.
When NOT to use
Do not use git restore when you want to undo commits or change branch pointers; use git reset or git revert instead. Also, avoid git restore if you want to keep changes but move them between branches; use git stash or git cherry-pick.
Production Patterns
In professional workflows, git restore is used to quickly discard local experimental changes before switching tasks. It is often combined with git status to review changes first. Teams use it to maintain clean working directories and avoid committing unfinished work.
Connections
Undo in Text Editors
Similar pattern of reverting changes to a previous state
Understanding git restore is like knowing how undo works in editors helps grasp the idea of discarding unwanted edits safely.
Version Control History
Builds on the concept of commits as snapshots
Knowing how commits save snapshots clarifies why git restore can reset files to those saved states.
Database Transactions
Shares the idea of rollback to a known good state
Seeing git restore as a rollback operation helps understand its role in maintaining consistent project states.
Common Pitfalls
#1Accidentally discarding staged changes when intending only to discard unstaged edits.
Wrong approach:git restore --staged
Correct approach:git restore # discard unstaged changes # and separately git restore --staged # unstage changes
Root cause:Confusing the --staged option and its effect on staging area versus working directory.
#2Using git restore to undo committed changes expecting to remove commits.
Wrong approach:git restore --source HEAD~1
Correct approach:git revert # to undo commits safely # or git reset --hard # to move HEAD and discard commits
Root cause:Misunderstanding git restore's scope limited to working directory and staging.
#3Running git restore . without checking which files will be discarded.
Wrong approach:git restore .
Correct approach:git status # check changes first git restore . # then discard if sure
Root cause:Not reviewing changes before discarding leads to unintended data loss.
Key Takeaways
git restore safely discards changes in your working directory by resetting files to their last committed state.
It separates concerns clearly from older commands, focusing only on file content restoration, making undo operations safer and easier.
You can discard unstaged changes, unstage files, or both, using different options with git restore.
Understanding the difference between working directory, staging area, and commits is essential to using git restore correctly.
Always review your changes before discarding to avoid losing important work unintentionally.

Practice

(1/5)
1. What does the command git restore <filename> do in a Git repository?
easy
A. It permanently deletes the specified file from the repository history.
B. It discards changes in the specified file and restores it to the last committed state.
C. It stages the specified file for the next commit.
D. It creates a new branch with the name of the specified file.

Solution

  1. Step 1: Understand the purpose of git restore

    The git restore command is used to undo changes in the working directory before committing.
  2. Step 2: Effect on the specified file

    Using git restore <filename> resets the file to its last committed state, discarding any edits made since then.
  3. Final Answer:

    It discards changes in the specified file and restores it to the last committed state. -> Option B
  4. Quick Check:

    Undo changes = git restore [OK]
Hint: Use git restore to undo file edits before commit [OK]
Common Mistakes:
  • Confusing restore with delete or branch creation
  • Thinking it stages files instead of discarding changes
  • Assuming it affects commit history
2. Which of the following is the correct syntax to discard changes in a file named app.js using git restore?
easy
A. git restore app.js
B. git restore --discard app.js
C. git restore -d app.js
D. git restore --reset app.js

Solution

  1. Step 1: Recall the basic syntax of git restore

    The command to discard changes in a file is simply git restore <filename> without extra flags.
  2. Step 2: Check the options given

    Options B, C, and D use incorrect or non-existent flags. Only git restore app.js uses the correct syntax.
  3. Final Answer:

    git restore app.js -> Option A
  4. Quick Check:

    Correct syntax = git restore filename [OK]
Hint: Use git restore filename without extra flags to discard changes [OK]
Common Mistakes:
  • Adding unnecessary flags like --discard or --reset
  • Using shorthand flags that don't exist
  • Confusing git restore with git reset
3. Given the following sequence of commands in a Git repository:
echo 'Hello' > file.txt
git add file.txt
echo 'World' >> file.txt
git restore file.txt
cat file.txt

What will be the output of cat file.txt?
medium
A. Hello
B. World
C. Hello\nWorld
D. file.txt: No such file or directory

Solution

  1. Step 1: Understand the commands before restore

    First, 'Hello' is written to file.txt and staged. Then 'World' is appended but not staged.
  2. Step 2: Effect of git restore on file.txt

    The git restore file.txt discards the unstaged changes, reverting file.txt to the last staged (or committed) state which contains only 'Hello'.
  3. Step 3: Output of cat file.txt

    After restore, file.txt contains only 'Hello'. So, cat file.txt outputs 'Hello'.
  4. Final Answer:

    Hello -> Option A
  5. Quick Check:

    Restore discards unstaged changes = Hello [OK]
Hint: Restore resets file to last staged or committed state [OK]
Common Mistakes:
  • Assuming restore keeps appended changes
  • Confusing staged and unstaged changes
  • Expecting both lines to appear after restore
4. You ran git restore file.txt but your changes were not discarded. What is the most likely reason?
medium
A. Git restore only works on new files, not modified ones.
B. The file was already committed and has no changes to discard.
C. You used the wrong filename in the command.
D. You have staged the changes, so restore does not affect them by default.

Solution

  1. Step 1: Understand git restore behavior with staged changes

    By default, git restore <file> only discards unstaged changes. Staged changes remain unless you add the --staged flag.
  2. Step 2: Analyze why changes were not discarded

    If changes were staged, running restore without --staged won't discard them, so the file appears unchanged.
  3. Final Answer:

    You have staged the changes, so restore does not affect them by default. -> Option D
  4. Quick Check:

    Restore ignores staged changes unless --staged used [OK]
Hint: Use --staged to discard staged changes with git restore [OK]
Common Mistakes:
  • Assuming restore discards staged changes without flags
  • Thinking restore works only on new files
  • Not checking if filename is correct
5. You have modified three files: index.html, style.css, and script.js. You staged index.html and style.css but want to discard only the unstaged changes in style.css and script.js. Which command will achieve this?
hard
A. git restore --discard style.css script.js
B. git restore --staged style.css script.js
C. git restore style.css script.js
D. git restore --staged style.css && git restore script.js

Solution

  1. Step 1: Identify which changes to discard

    You want to discard unstaged changes in style.css and script.js. Staged changes should remain.
  2. Step 2: Choose the correct git restore command

    git restore --discard style.css script.js uses invalid --discard flag. Options B and C use --staged which would discard staged changes, which is not desired. git restore style.css script.js discards unstaged changes only.
  3. Final Answer:

    git restore style.css script.js -> Option C
  4. Quick Check:

    Restore without --staged discards unstaged changes [OK]
Hint: Restore files without --staged to discard only unstaged changes [OK]
Common Mistakes:
  • Using --staged and discarding staged changes accidentally
  • Running separate commands unnecessarily
  • Using invalid flags like --discard