0
0
GitHow-ToBeginner · 3 min read

How to Discard Changes in a File with Git

To discard changes in a file in Git, use 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.
bash
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.

bash
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
Output
Hello World
⚠️

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.

bash
git checkout example.txt  # May fail or switch branches if -- is missing

# Correct usage in older Git versions:
git checkout -- example.txt
📊

Quick Reference

CommandDescription
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 statusCheck which files have changes

Key Takeaways

Use git restore <filename> to discard changes in a file safely.
In older Git versions, use git checkout -- <filename> to discard changes.
Discarding changes resets the file to the last committed state, losing uncommitted edits.
Always check git status before discarding to avoid losing important work.
Do not confuse git restore with git reset; they serve different purposes.