Hard reset of a single file – Dev

The best answers to the question “Hard reset of a single file” in the category Dev.

QUESTION:

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?

ANSWER:

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.

ANSWER:

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.

ANSWER:

To revert to upstream/master do:

git checkout upstream/master -- myfile.txt

ANSWER:

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