4913

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.

Mus
  • 5,994
  • 19
  • 75
  • 112
Hates_
  • 58,801
  • 6
  • 28
  • 37
  • 12
    After revert, don't forget `--cached` when checking `git diff`. [link](http://stackoverflow.com/questions/34051174/after-reverting-a-file-to-a-previous-revision-git-diff-shows-no-differences) – Geoffrey Hale Dec 02 '15 at 19:20
  • 6
    I found your question when I googled mine. But after I read the solution, I checked my log and found out, that I made thouse changes as a standalone commit, so I made git revert for that commit, and everything else stayed as I wanted it. Not a solution, just another way to do it sometimes. – sudo97 Aug 08 '17 at 14:08

33 Answers33

6735

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:

THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.

Greg Hewgill
  • 828,234
  • 170
  • 1,097
  • 1,237
  • 12
    @shadowhand: Is there a way to reverse that, so it's the version right after? – aliteralmind Apr 29 '14 at 12:57
  • 17
    @aliteralmind: No, unfortunately the Git history shortcut notation only goes backwards in history. – Greg Hewgill Apr 29 '14 at 18:02
  • 56
    If you're going to use a branch name for *abcde* (e.g. `develop`) you'll want `git checkout develop -- file/to/restore` (note the double dash) – Ohad Schneider Oct 07 '14 at 15:14
  • 8
    @aliteralmind: Actually, yes, there's a way to do it: "git log --reverse -1 --ancestry-path yourgitrev..master" and then use the appropriate options to just get the git rev. --ancestry-path will "draw a line" between two commits and -1 will show you just one version, and --reverse will ensure the first entry emitted is the oldest one. – Chris Cogdon Nov 19 '14 at 19:29
  • Be sure to checkout the revision hash that still has the file for which you're looking. If it was deleted in a revision, go to the hash at least one earlier than that. – C Fairweather Mar 30 '15 at 04:46
  • To automate the entire process of searching through the history of a file and checking out the appropriate commit-id in one git command, use [**`git prevision`**](http://stackoverflow.com/a/29980518/319204). – TheCodeArtist May 01 '15 at 01:49
  • 2
    If you want to delete your changes on this specific file, you can use `git checkout path/to/file`. If you don't specify a hash, HEAD is used. – Flows May 27 '16 at 11:49
  • 9
    Personally I find HEAD^ easier to type than HEAD~1 :) – juzzlin Jul 01 '16 at 11:38
  • Can we pass space-separated file-list right after the commit id? – Saurav Sahu Feb 03 '17 at 14:15
  • 1
    @juzzlin Or use `@^` instead of `HEAD^`. – Tom Hale Jul 28 '17 at 11:53
  • I also just realized that you have to be on the branch you pushed TO, not from. – ArielSD Aug 23 '17 at 18:09
  • The command above worked for me. However, auto-complete suggested a capitalized version of the file, and that produced "FILE1/TO/RESTORE did not match any file(s) known to git." Cases need to match what git has in the repository. – brentlightsey Nov 27 '17 at 20:56
  • How can I check 2 or more files? – Eduard Jan 14 '18 at 13:57
  • I was going to +1 you but clearly I have been here at least once before :D A very useful answer that maybe I should memorise! – Darragh Enright Jul 10 '18 at 12:40
  • 1
    Note for windows users: A relative path was not sufficient, I had to include the full path e.g. `/d/Repos/MyRepo/Folder1/Folder2/FileIWantToCheckout.json` – System.Cats.Lol Aug 24 '18 at 18:57
  • 1
    Incorrect answer, this does not REVERT. This only changes the file so the contents are the exact same as the commit you give it, you have to commit again for this to actually be implemented. – basickarl Dec 04 '18 at 11:30
  • 1
    Use `git checkout 5364aee~1 path/to/dir/*` to restore a whole directory of files to their version prior to 5364aee. – joshden Mar 05 '19 at 23:56
  • 1
    Can anyone explain the sidenote? Why is there a difference between switching between branches and discarding changes in the working directory? Doesn't switching a branch discard changes if the file names match? – Mark Bolster Apr 01 '19 at 15:21
  • 2
    @MarkBolster: The form of the command shown in the answer uses `git checkout --` for restoring specific file contents. Of course, the other completely different use of `git checkout` is for switching branches. It's unclear to me why somebody chose to use the *same* command name for two completely different things. (And no, switching branches never discards changes, if you try to do that, git will complain and ask you what you would like to do with the changes that would be overwritten.) – Greg Hewgill Apr 01 '19 at 19:45
  • 1
    this literally does nothing – Tyguy7 Jun 27 '19 at 23:05
  • 4
    @GregHewgill git has recently introduced `git restore`, it is the more appropriate command going forward. You might want to edit that into your answer. – tschoppi Oct 07 '19 at 11:08
  • 2
    @tschoppi: Thanks, I'll do that when the command is no longer marked as "experimental". – Greg Hewgill Oct 18 '19 at 08:06
  • I tried restoring a folder using `git checkout HEAD~2 -- my_folder/*` and it didn't work. – Aaron Franke May 15 '20 at 23:52
  • Ek dum gajab solution! It worked for me. – Takermania Dec 18 '20 at 07:11
643

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>
Chris Lloyd
  • 10,846
  • 7
  • 33
  • 31
  • 8
    'git checkout ' command has given me back my older version of the project exactly this for which I was searching Thanks Chris. – vidur punj Jan 27 '13 at 09:26
  • 2
    'git reset ' didn't change my specific file I wanted to change. Is there a way to checkout the version of the file, specifically, and not checkout the entire project? – Danny Feb 20 '13 at 01:18
  • 59
    To revert the file `git checkout ` worked better for me than `git reset` – Motti Strom Mar 07 '13 at 16:53
  • 3
    I wanted an early version of a single file because I had overwritten 150 lines with a badly chosen copy/paste. `git checkout ` worked for me. This should not be the accepted answer, IMHO. `git reset` did not. – harperville Feb 27 '14 at 20:58
  • Git reset without hard option does not modify working copy, which is why it didn't have any effect. Hard reset causes file to look exactly as in repository in specified commit, and WILL DISCARD your local changes, if any. – SteveB Nov 24 '14 at 12:54
  • 26
    cannot use `git reset` to reset single file, you will get an error `fatal: Cannot do hard reset with paths` – slier Dec 23 '14 at 17:11
  • 14
    What slier said: you cannot `git reset --hard `. This will error with `fatal: Cannot do hard reset with paths.` What Motti Strom said: use `git checkout ` – Hawkeye Parker Feb 06 '15 at 05:36
  • @HawkeyeParker uhh yes, we see that. Thanks for summarizing. – Adam Plocher Jul 17 '18 at 15:01
  • @Chris, **fatal: Cannot do hard reset with paths.** – Pacerier May 19 '20 at 23:27
  • I do not understand this, but thanks anyway, Chris Lloyd, this is very neat. – drakogemini2 Jan 06 '21 at 08:05
391

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]

George Stocker
  • 55,025
  • 29
  • 167
  • 231
foxxtrot
  • 10,664
  • 4
  • 25
  • 27
  • 27
    What is the difference between this answer, which has `--`, and the accepted one which does not? – 2rs2ts Oct 09 '14 at 00:20
  • 90
    In git, a ' -- ' before the file list tells git that all the next arguments should be interpreted as filenames, not as branch-names or anything else. It's a helpful disambiguator sometimes. – foxxtrot Oct 09 '14 at 14:32
  • 55
    The '--' is not only a git convention, but something you find in various places in on the *nix commandline. `rm -- -f` (remove a file named `-f`) seems to be the canonical example. [More detail here](http://stackoverflow.com/a/1192194/99717) – Hawkeye Parker Feb 06 '15 at 05:49
  • 7
    Just add to what @HawkeyeParker said, `rm` command uses getopt(3) to parse its arguments. `getopt` is the command to parse command arguments. http://www.gnu.org/software/libc/manual/html_node/Getopt.html – Devy Jul 14 '15 at 18:11
  • @HawkeyeParker you mean the *filename* is `-f`?! I'm assuming that's a very rare case right? – Honey Apr 04 '17 at 21:50
  • @foxxtrot You said `--` should be interpreted as files but after seeing Greg Hewgill 2nd answer below I'm confused.he suggests `git checkout -- foo` – Honey Apr 04 '17 at 21:55
  • 2
    @Honey Yes, that's what I mean, and yeah, probably not common at all. I've seen that example in various places, maybe just to make it sortof memorable: rm -f is well-known to be scary/dangerous. But, the point is, in *nix a file name _can_ start with a '-', and this will confuse various commandline interpreters which, when they see a '-', expect a command option to follow. It could be any file starting with '-'; e.g., "-mySpecialFile". – Hawkeye Parker Apr 05 '17 at 20:35
  • @Honey http://stackoverflow.com/questions/4715374/what-is-the-meaning-of-nix-and-what-is-its-relation-with-ruby – Hawkeye Parker Apr 07 '17 at 01:00
318
git checkout -- foo

That will reset foo to HEAD. You can also:

git checkout HEAD^ foo

for one revision back, etc.

Greg Hewgill
  • 828,234
  • 170
  • 1,097
  • 1,237
  • 13
    I'd suggest using syntax `git checkout -- foo` to avoid any mistakes if `foo` is anything special (like a directory or a file called `-f`). With git, if you're unsure, always prefix all files and directories with the special argument `--`. – Mikko Rantalainen Mar 18 '13 at 07:22
  • 9
    An additional note to Mikko's comment: `--` is not a git command and not special to git. It is a bash built-in to signify the end of command options. You can use it with many other bash commands too. – matthaeus Mar 04 '16 at 13:04
  • 17
    @matthaeus it's also neither specific to bash nor a shell feature at all. It's a convention implemented in many different commands (and supported by getopt). – Greg Hewgill Mar 04 '16 at 17:47
  • 3
    No, `--` is _not_ a builtin special word in bash. But it is a common convention supported by many commandline parsers and used by many CLIs, including git. – Emil Lundberg Sep 01 '19 at 14:20
127

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

git checkout HEAD file/to/restore
CDR
  • 7,636
  • 10
  • 44
  • 45
107

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.

Community
  • 1
  • 1
bbrown
  • 6,240
  • 5
  • 35
  • 42
94

If you know how many commits you need to go back, you can use:

git checkout master~5 image.png

This assumes that you're on the master branch, and the version you want is 5 commits back.

chim
  • 7,655
  • 3
  • 44
  • 58
Ron DeVera
  • 13,578
  • 5
  • 39
  • 36
84

I think I've found it....from http://www-cs-students.stanford.edu/~blynn/gitmagic/ch02.html

Sometimes you just want to go back and forget about every change past a certain point because they're all wrong.

Start with:

$ git log

which shows you a list of recent commits, and their SHA1 hashes.

Next, type:

$ git reset --hard SHA1_HASH

to restore the state to a given commit and erase all newer commits from the record permanently.

ZMorek
  • 689
  • 1
  • 8
  • 24
jdee
  • 10,282
  • 10
  • 36
  • 35
  • 24
    Git never removes anything. Your old commits are still there but unless there is a branch tip pointing at them they are not reachable anymore. git reflog will still show them until you clean your repository with git-gc. – Bombe Dec 17 '08 at 09:15
  • 1
    @Bombe: Thank you for the information. I had checked out an old version of a file. After reading your comment, I was able to use "gitref" to lookup the partial SHA1 hash, and use "checkout" to get back to the most recent version. Other git users might find this information helpful. – Winston C. Yang May 19 '10 at 14:53
  • 5
    possibly followed by a `git push --force` – bshirley Apr 18 '12 at 21:47
  • If after the above "git reset --hard SHA1_HASH", you do a "git status" and see Untracked files, and you want to get rid of them too. Run "git clean --force -d" – aerobiotic Apr 23 '12 at 18:28
  • 4
    If you have uncommitted changes, **you will loose** them if do a git reset --hard – Boklucius Apr 24 '12 at 15:30
  • i found this article that helped me get passed this issue: http://blogs.gnome.org/diegoe/2009/03/18/saving-your-neck-when-git-svn-dcommit-fails/ it seemed to work great and is very similar to this particular answer. – hellatan May 02 '12 at 14:18
  • 1
    Doesn't this reset ALL files? Not just a specific file? – aidan Jan 07 '14 at 23:50
  • 5
    @Bombe - "Git never removes anything. Your old commits are still there but unless there is a branch tip pointing at them they are not reachable anymore." - but commits like this are pruned after some set time, so "Git never removes anything" is untrue. – Bulwersator Apr 29 '14 at 07:07
  • @Bombe: `git reflog will still show them until you clean your repository with git-gc` – wrong. Reflog is a reference too and referenced commits will never be removed by git-gc. If you need to clean them right now, you have to do `git reflog expire --expire-unreachable=now --all` – Nick Volynkin Jun 26 '16 at 05:33
  • @NickVolynkin Your information is wrong; `git gc` *will* sometimes remove commits from the reflog. As the [`git-gc` man page](https://www.kernel.org/pub/software/scm/git/docs/git-gc.html) says, the configuration variables `gc.reflogExpire` and `gc.reflogExpireUnreachable` set age thresholds for deletion from the reflog. Entries older than those values will be deleted when `git gc` is run. The values default to 90 days and 30 days for reachable and unreachable commits. – Rory O'Kane Jun 19 '17 at 20:07
65

This worked for me:

git checkout <commit hash> file

Then commit the change:

git commit -a
v2k
  • 1,033
  • 9
  • 13
55

You have to be careful when you say "rollback". If you used to have one version of a file in commit $A, and then later made two changes in two separate commits $B and $C (so what you are seeing is the third iteration of the file), and if you say "I want to roll back to the first one", do you really mean it?

If you want to get rid of the changes both the second and the third iteration, it is very simple:

$ git checkout $A file

and then you commit the result. The command asks "I want to check out the file from the state recorded by the commit $A".

On the other hand, what you meant is to get rid of the change the second iteration (i.e. commit $B) brought in, while keeping what commit $C did to the file, you would want to revert $B

$ git revert $B

Note that whoever created commit $B may not have been very disciplined and may have committed totally unrelated change in the same commit, and this revert may touch files other than file you see offending changes, so you may want to check the result carefully after doing so.

  • I did this, but then a "git log file" would say that I was on the original commit, HEAD. It seemed that "git checkout" was failing. However, a git status showed that the file was actually changed and and a "git diff --staged file" would show the actual changes. Also, a "git status" showed the file changed as well. So don't use "git log" here to track which files changed. – Frederick Ollinger Jun 08 '18 at 18:35
  • @FrederickOllinger - that behavior makes sense, because `git log` shows *commits*, and you haven't *committed* the change (the reversion). If you do `git commit` after that revert, then `git log` will show the change. – ToolmakerSteve Jan 09 '21 at 21:40
48

As of git v2.23.0 there's a new git restore method which is supposed to assume part of what git checkout was responsible for (even the accepted answer mentions that git checkout is quite confusing). See highlights of changes on github blog.

The default behaviour of this command is to restore the state of a working tree with the content coming from the source parameter (which in your case will be a commit hash).

So based on Greg Hewgill's answer (assuming the commit hash is c5f567) the command would look like this:

git restore --source=c5f567 file1/to/restore file2/to/restore

Or if you want to restore to the content of one commit before c5f567:

git restore --source=c5f567~1 file1/to/restore file2/to/restore
mjarosie
  • 1,290
  • 15
  • 25
  • I suppose it's a dead thread kind of thing, but this is the correct "modern" answer. – Dan Apr 11 '21 at 00:13
40

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
leiyc
  • 881
  • 6
  • 19
Aaron Maenpaa
  • 105,677
  • 10
  • 91
  • 107
33

Here's how rebase works:

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

Assume you have

---o----o----o----o  master
    \---A----B       <my branch>

The first two commands ... commit git checkout git rebase master

... check out the branch of changes you want to apply to the master branch. The rebase command takes the commits from <my branch> (that are not found in master) and reapplies them to the head of master. In other words, the parent of the first commit in <my branch> is no longer a previous commit in the master history, but the current head of master. The two commands are the same as:

git rebase master <my branch>

It might be easier to remember this command as both the "base" and "modify" branches are explicit.

. The final history result is:

---o----o----o----o   master
                   \----A'----B'  <my branch>

The final two commands ...

git checkout master
git merge <my branch>

... do a fast-forward merge to apply all <my branch> changes onto master. Without this step, the rebase commit does not get added to master. The final result is:

---o----o----o----o----A'----B'  master, <my branch>

master and <my branch> both reference B'. Also, from this point it is safe to delete the <my branch> reference.

git branch -d <my branch>
George Stocker
  • 55,025
  • 29
  • 167
  • 231
cmcginty
  • 101,562
  • 37
  • 148
  • 155
25

First Reset Head For Target File

git reset HEAD path_to_file

Second Checkout That File

git checkout -- path_to_file
Gulshan Maurya
  • 990
  • 9
  • 21
  • 4
    +1, though not sure of the intent of resetting HEAD. It may or may not be needed. In my situation i only wanted to revert one particular file to the version in repository (which keeping remaining local changes intact. Just running the second step above was sufficient for me – fkl Jan 19 '18 at 23:56
  • Yes I only need to run the 2nd command. Like --> https://www.shellhacks.com/git-revert-file-to-previous-commit/ – javaPlease42 May 30 '19 at 17:07
25
  1. Git revert file to a specific commit
git checkout Last_Stable_commit_Number -- fileName

2.Git revert file to a specific branch

git checkout branchName_Which_Has_stable_Commit fileName
cxxl
  • 4,014
  • 3
  • 25
  • 46
ireshika piyumalie
  • 1,546
  • 18
  • 21
22

In the case that you want to revert a file to a previous commit (and the file you want to revert already committed) you can use

git checkout HEAD^1 path/to/file

or

git checkout HEAD~1 path/to/file

Then just stage and commit the "new" version.

Armed with the knowledge that a commit can have two parents in the case of a merge, you should know that HEAD^1 is the first parent and HEAD~1 is the second parent.

Either will work if there is only one parent in the tree.

21

git-aliases, awk and shell-functions to the rescue!

git prevision <N> <filename>

where <N> is the number of revisions of the file to rollback for file <filename>.
For example, to checkout the immediate previous revision of a single file x/y/z.c, run

git prevision -1 x/y/z.c

How git prevision works?

Add the following to your gitconfig

[alias]
        prevision = "!f() { git checkout `git log --oneline $2 |  awk -v commit="$1" 'FNR == -commit+1 {print $1}'` $2;} ;f"

The command basically

  • performs a git log on the specified file and
  • picks the appropriate commit-id in the history of the file and
  • executes a git checkout to the commit-id for the specified file.

Essentially, all that one would manually do in this situation,
wrapped-up in one beautiful, efficient git-alias - git-prevision

Community
  • 1
  • 1
TheCodeArtist
  • 19,131
  • 3
  • 60
  • 123
21

Many suggestions here, most along the lines of git checkout $revision -- $file. A couple of obscure alternatives:

git show $revision:$file > $file

And also, I use this a lot just to see a particular version temporarily:

git show $revision:$file

or

git show $revision:$file | vim -R -

(OBS: $file needs to be prefixed with ./ if it is a relative path for git show $revision:$file to work)

And the even more weird:

git archive $revision $file | tar -x0 > $file
Peter V. Mørch
  • 9,433
  • 5
  • 46
  • 65
  • 2
    This is a nice alternative if you're not sure which commit version you want and need to "peek" around without overwriting your working directory. – wisbucky Feb 16 '18 at 22:25
20

I have to plug EasyGit here, which is a wrapper to make git more approachable to novices without confusing seasoned users. One of the things it does is give more meanings to git revert. In this case, you would simply say:

eg revert foo/bar foo/baz

Aristotle Pagaltzis
  • 101,052
  • 21
  • 94
  • 96
  • 1
    It should be `eg revert --in REVISON -- FILENAME`. The `--in` is important. For the Windows users out there: Open git bash. Execute `echo %PATH`. The first path should be in your user directory ending with `bin`. Create that path. Store [eg](https://people.gnome.org/~newren/eg/download/latest/eg) there. Name it `eg`. Not `eg.txt`. – koppor Dec 02 '16 at 07:13
18

Note, however, that git checkout ./foo and git checkout HEAD ./foo are not exactly the same thing; case in point:

$ echo A > foo
$ git add foo
$ git commit -m 'A' foo
Created commit a1f085f: A
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 foo
$ echo B >> foo
$ git add foo
$ echo C >> foo
$ cat foo
A
B
C
$ git checkout ./foo
$ cat foo
A
B
$ git checkout HEAD ./foo
$ cat foo
A

(The second add stages the file in the index, but it does not get committed.)

Git checkout ./foo means revert path ./foo from the index; adding HEAD instructs Git to revert that path in the index to its HEAD revision before doing so.

George Stocker
  • 55,025
  • 29
  • 167
  • 231
Damien Diederen
  • 2,464
  • 1
  • 17
  • 7
15

For me none of the reply seemed really clear and therefore I would like to add mine which seems super easy.

I have a commit abc1 and after it I have done several (or one modification) to a file file.txt.

Now say that I messed up something in the file file.txt and I want to go back to a previous commit abc1.

1.git checkout file.txt : this will remove local changes, if you don't need them

2.git checkout abc1 file.txt : this will bring your file to your wanted version

3.git commit -m "Restored file.txt to version abc1" : this will commit your reversion.

  1. git push : this will push everything on the remote repository

Between the step 2 and 3 of course you can do git status to understand what is going on. Usually you should see the file.txt already added and that is why there is no need of a git add.

desmond13
  • 2,106
  • 2
  • 21
  • 30
  • 2
    OK so I guess steps 1. and 2. are mutually exclusive: if abc1 is your last commit there is no need for 2. and if there were other commits after abc1 you can directly do 2. – Jean Paul Nov 15 '17 at 10:58
11

In order to go to a previous commit version of the file, get the commit number, say eb917a1 then

git checkout eb917a1 YourFileName

If you just need to go back to the last commited version

git reset HEAD YourFileName
git checkout YourFileName

This will simply take you to the last committed state of the file

shah1988
  • 2,456
  • 1
  • 17
  • 21
11

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

Vince
  • 2,844
  • 1
  • 25
  • 26
10

git checkout ref|commitHash -- filePath

e.g.

git checkout HEAD~5 -- foo.bar
or 
git checkout 048ee28 -- foo.bar
Amos Folarin
  • 1,826
  • 18
  • 18
10

This is a very simple step. Checkout file to the commit id we want, here one commit id before, and then just git commit amend and we are done.

# git checkout <previous commit_id> <file_name>
# git commit --amend

This is very handy. If we want to bring any file to any prior commit id at the top of commit, we can easily do.

Abhishek Dwivedi
  • 4,309
  • 3
  • 12
  • 18
  • Thanks, Abhishek. Based on your answer, I made this Shellscipt: https://gist.github.com/ivanleoncz/c20033e5f4b24304cbc39e0bac1d43e8 Feel free to improve :). – ivanleoncz Jul 22 '20 at 00:22
8

Use git log to obtain the hash key for specific version and then use git checkout <hashkey>

Note: Do not forget to type the hash before the last one. Last hash points your current position (HEAD) and changes nothing.

vicvicvic
  • 5,475
  • 3
  • 31
  • 50
mustafakyr
  • 81
  • 1
  • 1
7

You can do it in 4 steps:

  1. revert the entire commit with the file you want to specifically revert - it will create a new commit on your branch
  2. soft reset that commit - removes the commit and moves the changes to the working area
  3. handpick the files to revert and commit them
  4. drop all other files in your work area

What you need to type in your terminal:

  1. git revert <commit_hash>
  2. git reset HEAD~1
  3. git add <file_i_want_to_revert> && git commit -m 'reverting file'
  4. git checkout .

good luck

Nir M.
  • 129
  • 1
  • 4
  • doesn't that revert ALL changes? – arcee123 Oct 29 '18 at 13:22
  • 1
    @arcee123 Yes, but the subsequent reset undoes the revert of all changes. The problem is that `git-revert` only operates on the whole repo, so to compensate we have to undo everything else. – Timothy Feb 05 '19 at 22:01
  • 2
    I recommend using: 1. `git revert --no-commit ` 2. `git reset HEAD` This saves an extra commit floating around and does all the changes only in your working directory. – Timothy Feb 05 '19 at 22:04
  • @greg-hewgill 's answer is better and spot on. This one is lousy and should not be used. – Daniel Tranca Feb 28 '19 at 16:27
  • This is exactly what is needed for a true revert of specific files. I needed to undo changes to a few files from an earlier commit that had already been pushed to the remote repository. I reverted, reset, and committed the result: `git revert _oldcommit_ --no-commit` `git reset -- _unchanged1_ _unchanged2_ ...` `git commit -m "branch without changes to specific files"` The new branch tip reflected all changes except the reverted files. – Suncat2000 Mar 21 '19 at 15:30
  • @DanielTranca Greg Hewgill's answer is not better if you want to revert changes. There may be intervening commits that changed other portions of the files. Nir M.'s answer addresses reverting only what was changed to the specific files in a single commit; his is the better answer to reverting, which I confirmed by arriving at equivalent steps myself. – Suncat2000 Mar 21 '19 at 15:40
7

Obviously someone either needs to write an intelligible book on git, or git needs to be better explained in the documentation. Faced with this same problem I guessed that

cd <working copy>
git revert master

would undo the last commit which is seemed to do.

Ian

Chadwick
  • 12,048
  • 7
  • 46
  • 65
Ian Davis
  • 71
  • 1
  • 1
5
git revert <hash>

Will revert a given commit. It sounds like you think git revert only affects the most recent commit.

That doesn't solve your problem, if you want to revert a change in a specific file and that commit changed more than that file.

Otto
  • 16,619
  • 14
  • 54
  • 62
5

if you commit a wrong file in your last commits follow the instruction :

  1. open source tree, change to this commit

open source tree

  1. change the lines and find your commit that the wrong file sent as commit

enter image description here

  1. you can see the list of your changes in that commit list of files in the source tree
  2. select it and then click on ... buttons right-hand side ... click reverse file
  3. then you can see it on file status tab at the bottom left-hand side then click unstage:

file status tab

  1. open your visual studio code and revert back by committing your removed files
  2. after them all, you can see results in your last commit in the source tree

enter image description here

saber tabatabaee yazdi
  • 2,078
  • 3
  • 26
  • 40
3

Here is my way.

a) In Android Studio, open the file.

b) git -> Show History, find the previous commit I want to revert to. Get the commit_id (i.e. commit hash).

c) git checkout commit_id file_path

FelixSFD
  • 5,456
  • 10
  • 40
  • 106
Francis Bacon
  • 1,928
  • 1
  • 18
  • 30
2

If you're using Git Extensions and you only want to revert to the parent commit for the file, you can select the commit that contains the changes you want to revert, then select the 'Diff' tab in the details pane, right-click the file you want to revert, then 'Reset file(s) to' ...., then 'A' (the parent)

Chris Halcrow
  • 21,541
  • 11
  • 115
  • 145
2
  • Run the following command that does a soft reset and the changes comes to your local.
git reset --soft HEAD^1
  • See the status of files that you previously committed that comes to your local and then make the change.
 git status
  • Commit and push the file after making the changes.

  • Previous commit history for the wrong committed files will not be shown

Dev-lop-er
  • 119
  • 1
  • 10