間違えて[[Hard reset (Git)|Hard reset]]してしまったときに、コミットせず[[ステージング (Git)|ステージング]]だけしていた内容を取り戻す方法。[[git fsck --lost-found]]を使う。 > [!info] > コミットした変更の場合は [[Hard resetしたコミットを取り戻す (Git)|Hard resetしたコミットを取り戻す]] を参照。 ## 前提条件の作成 コミットを3回した状況を考える。 ```mermaid gitGraph: commit id: "初コミット" commit id: "コミット2" commit id: "コミット3" type: HIGHLIGHT ``` [[reflog (Git)|reflog]]はこう。 ```console $ git reflog e91079b HEAD@{0}: commit: コミット3 518c7ac HEAD@{1}: commit: コミット2 64c3664 HEAD@{2}: commit (initial): 初コミット ``` **`README.md` に変更を加えてステージングしてから**、間違えて `コミット3` (最新のコミット) の状態に [[Hard reset (Git)|Hard reset]] してしまったとする。 ```console git reset --hard HEAD ``` [[コミットグラフ]]はもちろん変わらない。 ```mermaid gitGraph: commit id: "初コミット" commit id: "コミット2" commit id: "コミット3" type: HIGHLIGHT ``` [[reflog (Git)|reflog]]はこんな感じ。 ```console $ git reflog e91079b HEAD@{0}: reset: moving to HEAD e91079b HEAD@{1}: commit: コミット3 518c7ac HEAD@{2}: commit: コミット2 64c3664 HEAD@{3}: commit (initial): 初コミット ``` ## 復活の仕方 [[git fsck --lost-found]] で dangling blob オブジェクトを `.git/lost-found` 配下に作成する。 ```console $ git fsck --lost-found Checking ref database: 100% (1/1), done. Checking object directories: 100% (256/256), done. dangling blob 77132f261bb4aceb2076dab655b67b46339cae69 ``` `.git/lost-found/other` に作成されていることを確認。 ```console $ tree .git/lost-found  .git/lost-found └──  other └── 󰡯 77132f261bb4aceb2076dab655b67b46339cae69 ``` このファイルが[[Hard reset (Git)|Hard reset]]前の状態なので復元すればよい。 ```console $ cat .git/lost-found/other/77132f261bb4aceb2076dab655b67b46339cae69 # README - commit2 - commit3 - commit4 ``` なお、`git show` でリダイレクトしてもよい。 ```console $ git show 77132f261bb4aceb2076dab655b67b46339cae69 # README - commit2 - commit3 - commit4 ```