git reset--hard後恢復暫存區文件

最近使用git時,遇到了一個問題,還是自己用的不6,,本來想把pom.xml文件直接replace掉,結果把所有文件都替了,導致原先緩存區裏(只add,沒有commit)的文件全部被還原了,當時還沒在意,心想用reflog,再reset就好了,特麼後來纔想起來,都沒COMMIT,根本沒法弄呀,網上查了不少資料都是COMMIT以後的,我這個只進行了ADD操作,急壞了。。後來查詢到了幾個命令,沒想到還真恢復了

git reset --hard 是把本地庫裏的文件全部替換到了工作空間裏

下面是stackoverFlow上一些人提供的方法

If you didn't already commit your local changes (or at least stage them via `git add`, they're gone. `git reset --hard` is a destructive operation for uncommitted changes.

If you did happen to stage them, but didn't commit them, try `git fsck --lost-found` and then search through the contents of .git/lost-found - it will contain all of the objects that aren't referenced by a known commit, and may include versions of files that were staged.

You can recover anything you git added, with git fsck --lost-found and poke around in .git/lost-found.  find .git/objects -type f | xargs ls -lt | sed 60q will give you the last 60 things to get added to the repo, that'll help.

Anything you didn't git add is gone as surely as if you'd deleted it yourself.


  1. 執行 find .git/objects -type f | xargs ls -lt | sed 60q ,這裏60q 的意思是最近60次的add,然後會出來:

    $ find .git/objects -type f | xargs ls -lt | sed 60q

    -r—r—r— 1 Y Administ 222 Feb 3 21:00 .git/objects/02/18fb7591

    36a0ee550d2e4d179f01bd75af48a0

    -r—r—r— 1 Y Administ 176 Feb 3 21:00 .git/objects/5c/cb94ce63

    fd5196db10dffa6bab149c8b30546e

    -r—r—r— 1 Y Administ 77 Feb 3 21:00 .git/objects/d5/177a8da3

    96b5d6450d2c8e6ecf2f3ad8e41cd2

    -r—r—r— 1 Y Administ 1387 Feb 3 21:00 .git/objects/e0/7e9099c0

    b27a4dd1a432db0bbf2112ca544ebd

    -r—r—r— 1 Y Administ 5480 Feb 3 20:38 .git/objects/74/ea02bfa7

    353be6095959503abdd7dc0a178f53

    -r—r—r— 1 Y Administ 2701 Feb 3 20:38 .git/objects/7a/d366bac4

    91f6793d9b7da0cc3e7fb5ba26d403

    -r—r—r— 1 Y Administ 2597 Feb 3 20:38 .git/objects/a7/9c139160

    fa387b365629ead63f5818177d2e48


此處僅僅截取一部分信息,然後就是恢復了。

  1. 使用 git cat-file -p ID > a.md ,解釋一下這個命令,就是將ID所示的文件讀取出來重定向保存到 a.md 文件內,ID是objects後面的一串東西,比如第一個就是 0218fb759136a0ee550d2e4d179f01bd75af48a0 。(PS:需要將之間的/ 去掉)。
  2. 恢復的文件就在項目目錄裏a.md中,這樣緩存區的文件就回來了,至於連add都沒有的同學。。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章