Hard reset of a single file
Since Git 2.23 (August 2019) you can use restore
(more info):
git restore pathTo/MyFile
The above will restore MyFile
on HEAD
(the last commit) on the current branch.
If you want to get the changes from other commit you can go backwards on the commit history. The below command will get MyFile
two commits previous to the last one. You need now the -s
(--source
) option since now you use master~2
and not master
(the default) as you restore source:
git restore -s master~2 pathTo/MyFile
You can also get the file from other branch!
git restore -s my-feature-branch pathTo/MyFile
To reset both the working copy of my-file.txt
and its state in the Git index to that of HEAD:
git checkout HEAD -- my-file.txt
--
means "treat every argument after this point as a filename". More details in this answer. Thanks to VonC for pointing this out.
Reset to head:
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.
Reset to index:
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.