Advertisement
Advertisement


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


Question

I have made some changes to a file which has been committed a few times as part of a group of files, but now want to reset/revert the changes on it back to a previous version.

I have done a git log along with a git diff to find the revision I need, but just have no idea how to get the file back to its former state in the past.

2019/07/25
1
4631
7/25/2019 9:18:54 PM

Accepted Answer

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).

2020/03/26
6289
3/26/2020 4:24:37 PM

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>
2008/12/17

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]

2014/04/29

git checkout -- foo

That will reset foo to HEAD. You can also:

git checkout HEAD^ foo

for one revision back, etc.

2013/03/18

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

git checkout HEAD file/to/restore
2012/01/14

I had the same issue just now and I found this answer easiest to understand (commit-ref is the SHA value of the change in the log you want to go back to):

git checkout [commit-ref] [filename]

This will put that old version in your working directory and from there you can commit it if you want.

2017/05/23

Source: https://stackoverflow.com/questions/215718
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]