How to Discard Changes in a File with Git
git restore <filename> to revert the file to the last committed version. For older Git versions, use git checkout -- <filename> to achieve the same effect.Syntax
The main command to discard changes in a file is git restore <filename>. This command resets the file in your working directory to match the last commit, removing any edits you made.
Alternatively, in older Git versions, you can use git checkout -- <filename> which works similarly.
<filename>: The path to the file you want to discard changes from.
git restore <filename>
Example
This example shows how to discard changes in a file named example.txt. Suppose you edited the file but want to undo those edits and return to the last saved version in Git.
echo "Hello World" > example.txt git add example.txt git commit -m "Add example.txt" echo "Changed content" > example.txt # Discard changes in example.txt git restore example.txt # Check file content cat example.txt
Common Pitfalls
One common mistake is trying to discard changes without specifying the file, which can lead to unexpected results or no action.
Another pitfall is confusing git restore with git reset. The git restore command only affects your working files, while git reset changes the commit history or staging area.
Also, using git checkout <filename> without the double dash -- in older Git versions can cause errors or unexpected behavior.
git checkout example.txt # May fail or switch branches if -- is missing # Correct usage in older Git versions: git checkout -- example.txt
Quick Reference
| Command | Description |
|---|---|
| git restore | Discard changes in the file, revert to last commit |
| git checkout -- | Older Git versions: discard changes in the file |
| git reset | Unstage changes but keep edits in the file |
| git status | Check which files have changes |
Key Takeaways
git restore <filename> to discard changes in a file safely.git checkout -- <filename> to discard changes.git status before discarding to avoid losing important work.git restore with git reset; they serve different purposes.