I currently have three modified files in my working directory. However I want one of them to be reset to the HEAD status.
In SVN, I'd use svn revert <filename>
(followed by svn update <filename>
if needed) but in Git I should use git reset --hard
. However this command cannot operate on a single file.
Is there any way in Git to discard the changes to a single file and overwrite it with a fresh HEAD copy?
git checkout, git reset, and git restore are commands that can help you revert to a previous version not just of your codebase, but of individual files, too.
Summary. To review, git reset is a powerful command that is used to undo local changes to the state of a Git repo. Git reset operates on "The Three Trees of Git". These trees are the Commit History ( HEAD ), the Staging Index, and the Working Directory.
You can use the following command:
git checkout HEAD -- my-file.txt
... which will update both the working copy of my-file.txt
and its state in the index with that from HEAD.
--
basically means: treat every argument after this point as a file name. More details in this answer. Thanks to VonC for pointing this out.
To hard reset a single file to HEAD:
git checkout @ -- myfile.ext
Note that @
is short for HEAD
. An older version of git may not support the short form.
To hard reset a single file to the index, assuming the index is non-empty, otherwise to HEAD:
git checkout -- myfile.ext
The point is that to be safe, you don't want to leave out @
or HEAD
from the command unless you specifically mean to reset to the index only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With