Restore file from old commit in git

人盡茶涼 提交于 2019-11-27 08:59:43

问题


I have an old commit that I did a few weeks ago. I want to restore only a single file from that commit. What do I do?


回答1:


git checkout 'master@{7 days ago}' -- path/to/file.txt

This will not alter HEAD, it will just overwrite the local file path/to/file.txt

See man git-rev-parse for possible revision specifications there (of course a simple hash (like dd9bacb) will do nicely)

Don't forget to commit the change (after a review...)




回答2:


  1. Check out the file from your old commit via git checkout [Revision_Key] -- path/to/file.
  2. Add, commit, push as appropriate.



回答3:


I needed to restore a recent file committed into git. So just to reiterate and give another perspective, you need to do this by running the following two steps:

  1. git log -3
    This shows the three most recent commits. Read the comments and the author's name so you narrow down what exact version you want. Write down that long commit id (i.e. b6b94f2c19c456336d60b9409fb1e373036d3d71) for the commit version you want.

  2. git checkout b6b94f2c19c456336d60b9409fb1e373036d3d71 -- myfile.java
    Pass the commit id AND the file name you want to restore. Make sure you have a space before and after the double hyphen.

There are many other ways to do it. But this one is the simpler one I can remember. Hope that helps.

NOTE: If you are inside your project path/folder then is not necessary to type the full file's path in the checkout command.




回答4:


All answers mention git checkout <tree-ish> -- <pathspec>. 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. 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).

Assuming the commit hash is abcdef the command would look like this:

git restore --source=abcdef file_name

which (by default) puts it in working tree. If you want to put the change directly in index so it can be committed straight away:

git restore --source=abcdef --worktree --staged file_name

or with short option names:

git restore -s=abcdef -W -S file_name


来源:https://stackoverflow.com/questions/6624036/restore-file-from-old-commit-in-git

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!