Hard reset of a single file
What commands allow us to discard local changes and restore a specific file back to its last committed state without affecting the rest of the project?
Sometimes while working with Git, you may want to undo changes only for a specific file without resetting your entire project. This is where performing a hard reset on a single file becomes useful. Git provides a couple of simple commands to restore that file to its last committed version.
Hard reset a single modified file to the latest commit:
git checkout -- filename- Discards any local changes permanently
- Restores the file from the latest commit in the current branch
If the file has been staged already:
git reset HEAD filename
git checkout -- filename- First command un-stages the file
- Second command resets it to the committed state
Reset file from a specific commit or branch:
git checkout commit_hash -- filename- Useful if you want the version from an older commit
or
git restore filename(Recommended in newer Git versions)
Why perform a hard reset on a single file?
- Fix accidental edits without touching the whole codebase
- Recover a file quickly if it becomes corrupted or messy
- Helps maintain clean and controlled version history
Warning: A hard reset will permanently remove your uncommitted changes for that file. Make sure you don’t need those edits before running the command.
In summary, Git makes it easy to reset just one file using commands like git checkout -- file or the modern git restore. This keeps the rest of your project safe while restoring only what you need.