How to revert a specific file to a previous version in Git
· Category: Git
Short answer
Use git checkout <commit> -- <file> to restore a specific file to the state it had in a previous commit.
Steps
- Find the commit hash:
git log --oneline -- file.txt
- Restore the file:
git checkout abc1234 -- file.txt
- Stage and commit the restoration:
git add file.txt
git commit -m "Restore file.txt to previous version"
Tips
- This creates a new commit with the old file content.
- Use
git restore --source=abc1234 file.txtas a modern alternative. - Restoring a file does not affect other files or branch history.
Common issues
- Forgetting to commit leaves the file staged but uncommitted.
- Make sure you are checking out from the correct commit hash.