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 versio
git checkout ref|commitHash -- filePath
e.g.
git checkout HEAD~5 -- foo.bar
or
git checkout 048ee28 -- foo.bar
You can do it in 4 steps:
What you need to type in your terminal:
git revert <commit_hash>
git reset HEAD~1
git add <file_i_want_to_revert>
&& git commit -m 'reverting file'
git checkout .
good luck
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>
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.
Amusingly, git checkout foo
will not work if the working copy is in a directory named foo
; however, both git checkout HEAD foo
and git checkout ./foo
will:
$ pwd
/Users/aaron/Documents/work/foo
$ git checkout foo
D foo
Already on "foo"
$ git checkout ./foo
$ git checkout HEAD foo
Many answers here claims to use git reset ... <file>
or git checkout ... <file>
but by doing so, you will loose every modifications on <file>
committed after the commit you want to revert.
If you want to revert changes from one commit on a single file only, just as git revert
would do but only for one file (or say a subset of the commit files), I suggest to use both git diff
and git apply
like that (with <sha>
= the hash of the commit you want to revert) :
git diff <sha>^ <sha> path/to/file.ext | git apply -R
Basically, it will first generate a patch corresponding to the changes you want to revert, and then reverse-apply the patch to drop those changes.
Of course, it shall not work if reverted lines had been modified by any commit between <sha1>
and HEAD
(conflict).