markdown 如何从项目git commit history中查找和恢复已删除的文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 如何从项目git commit history中查找和恢复已删除的文件相关的知识,希望对你有一定的参考价值。

## Question:
Once upon a time, there was a file in my project that I would now like to be able to get.

The problem is: I have no idea of when have I deleted it and on which path was it at.

How can I locate the commits of this file when it existed?

## Answer: 
Suppose you want to recover a file called MyFile, but are uncertain of its path (or its extension, for that matter):

Prelim.: **Avoid confusion by stepping to the git root**

A nontrivial project may have multiple directories with similar or identical names.

`> cd <project-root>`   

**Find the full path**

`git log --diff-filter=D --summary | grep delete | grep MyFile`

> `delete mode 100644 full/path/to/MyFile.js`

`full/path/to/MyFile.js` is the path & file you're seeking.

**Determine all the commits that affected that file**

`git log --oneline --follow -- full/path/to/MyFile.js`

>`bd8374c Some helpful commit message`   
> `ba8d20e Another prior commit message affecting that file`   
> `cfea812 The first message for a commit in which that file appeared.`

**Checkout the file**

If you choose the first-listed commit (the last chronologically, here bd8374c), the file will not be found, since it was deleted in that commit.

 `git checkout bd8374c -- full/path/to/MyFile.js`

> `error: pathspec 'full/path/to/MyFile.js' did not match any file(s) known to git.`

Just select the preceding (append a caret) commit:   
`git checkout bd8374c^ -- full/path/to/MyFile.js`

---


Note, this was one of several answers on [StackOverflow](https://stackoverflow.com/a/42582877/6412747) -- I liked it best but there were several others worth reading. 

以上是关于markdown 如何从项目git commit history中查找和恢复已删除的文件的主要内容,如果未能解决你的问题,请参考以下文章

markdown Git Commit消息表情符号

markdown Git Commit消息表情符号

markdown git commit提交规范

markdown 在`git push`之后在本地和远程撤消`git commit`

无法从 git commit 中删除文件

markdown 一些命令在命令行上获取存储库的git commit日志统计信息。