git - How can I reset or revert a file to a specific revision?

ID : 52

viewed : 228

Tags : gitversion-controlgit-checkoutgit

Top 5 Answer for git - How can I reset or revert a file to a specific revision?

vote vote


Assuming the hash of the commit you want is c5f567:

git checkout c5f567 -- file1/to/restore file2/to/restore 

The git checkout man page gives more information.

If you want to revert to the commit before c5f567, append ~1 (where 1 is the number of commits you want to go back, it can be anything):

git checkout c5f567~1 -- file1/to/restore file2/to/restore 

As a side note, I've always been uncomfortable with this command because it's used for both ordinary things (changing between branches) and unusual, destructive things (discarding changes in the working directory).

There is also a new git restore command that is specifically designed for restoring working copy files that have been modified. If your git is new enough you can use this command, but the documentation comes with a warning:


vote vote


You can quickly review the changes made to a file using the diff command:

git diff <commit hash> <filename> 

Then to revert a specific file to that commit use the reset command:

git reset <commit hash> <filename> 

You may need to use the --hard option if you have local modifications.

A good workflow for managaging waypoints is to use tags to cleanly mark points in your timeline. I can't quite understand your last sentence but what you may want is diverge a branch from a previous point in time. To do this, use the handy checkout command:

git checkout <commit hash> git checkout -b <new branch name> 

You can then rebase that against your mainline when you are ready to merge those changes:

git checkout <my branch> git rebase master git checkout master git merge <my branch> 
vote vote


You can use any reference to a git commit, including the SHA-1 if that's most convenient. The point is that the command looks like this:

git checkout [commit-ref] -- [filename]

vote vote


git checkout -- foo 

That will reset foo to HEAD. You can also:

git checkout HEAD^ foo 

for one revision back, etc.

vote vote


And to revert to last committed version, which is most frequently needed, you can use this simpler command.

git checkout HEAD file/to/restore 

Top 3 video Explaining git - How can I reset or revert a file to a specific revision?