How do I revert a modified file to its previous revision at a specific commit hash (which I determined via git log
and git diff
)?
Solution:1
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).
Solution:2
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>
Solution:3
Git is very flexible. You shouldn’t need hundreds of branches to do what you are asking. If you want to revert the state all the way back to the 2nd change (and it is indeed a change that was already committed and pushed), use git revert
. Something like:
git revert a4r9593432
where a4r9593432 is the starting characters of the hash of the commit you want to back out.
If the commit contains changes to many files, but you just want to revert just one of the files, you can use git reset
(the 2nd or 3rd form):
git reset a4r9593432 -- path/to/file.txt
# the reverted state is added to the staging area, ready for commit
git diff --cached path/to/file.txt # view the changes
git commit
git checkout HEAD path/to/file.txt # make the working tree match HEAD
But this is pretty complex, and git reset is dangerous. Use git checkout <hash> <file path>
instead, as Jefromi suggests.
If you just want to view what the file looked like in commit x, you can use git show
:
git show a4r9593432:path/to/file.txt
For all of the commands, there are many ways to refer to a commit other than via the commit hash (see Naming Commits in the Git User Manual).