0
0
Gitdevops~5 mins

git restore to discard working changes - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you make changes to files in your project but then decide you don't want to keep those changes. The git restore command helps you throw away those changes and go back to the last saved version.
When you accidentally edit a file and want to undo all your edits before saving.
When you try out some code changes but decide they are not needed and want to discard them.
When you want to reset a file to the last committed state without affecting other files.
When you want to clean up your working folder before switching branches.
When you want to undo changes in a specific file without touching the rest of your project.
Commands
Check which files have changes that are not saved to the repository yet.
Terminal
git status
Expected OutputExpected
On branch main Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: example.txt no changes added to commit (use "git add" and/or "git commit -a")
Discard all changes made to example.txt and restore it to the last saved version in the repository.
Terminal
git restore example.txt
Expected OutputExpected
No output (command runs silently)
Verify that example.txt no longer has any changes and is back to the last committed state.
Terminal
git status
Expected OutputExpected
On branch main nothing to commit, working tree clean
Key Concept

If you remember nothing else, remember: git restore lets you undo changes in your files by resetting them to the last saved version.

Common Mistakes
Using git restore without specifying the file name.
Git will not know which file to restore and will show an error or do nothing.
Always specify the exact file or files you want to discard changes for, like git restore example.txt.
Trying to undo changes that have already been staged with git add using git restore.
git restore by default only affects the working directory, not the staging area.
Use git restore --staged <file> to unstage changes, or git restore --staged and git restore to fully discard.
Summary
Use git status to see which files have unsaved changes.
Use git restore <file> to discard changes and reset the file to the last commit.
Check again with git status to confirm the file is clean.