Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hard reset of a single file

Tags:

git

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?

like image 276
Emiliano Avatar asked Aug 22 '11 12:08

Emiliano


People also ask

Can you git reset a single file?

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.

What does git reset HEAD file do?

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.


2 Answers

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.

like image 100
Mark Longair Avatar answered Sep 30 '22 07:09

Mark Longair


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.

like image 23
Asclepius Avatar answered Sep 30 '22 07:09

Asclepius