Restoring deleted files in Git

From LemonWiki共筆
Revision as of 18:01, 4 March 2026 by Planetoid (talk | contribs) (Created page with "= 復原 GIT 誤刪除的檔案 = == 復原方法 == === 方法一:透過 Fork 右鍵選單 === 使用 [https://git-fork.com/ Fork Git 客戶端軟體],並且對 <code>Deleted.file</code> 右鍵選擇了 '''Reset File to'''。 # 右鍵點擊被刪除的檔案 # 選擇 '''Reset File to''' → <code>State at Commit...</code> 或 <code>State Before Commit...</code> #* <code>State at Commit...</code> → 還原到某個特定 commit 的狀態 #* <code>State Before Co...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

復原 GIT 誤刪除的檔案

復原方法

方法一:透過 Fork 右鍵選單

使用 Fork Git 客戶端軟體,並且對 Deleted.file 右鍵選擇了 Reset File to

  1. 右鍵點擊被刪除的檔案
  2. 選擇 Reset File toState at Commit...State Before Commit...
    • State at Commit... → 還原到某個特定 commit 的狀態
    • State Before Commit... → 還原到該 commit 之前的狀態

> 建議: 直接用選單,點 State Before Commit... 即可快速還原到刪除前的狀態。

方法二:命令列

> 注意: 檔案路徑需要完全一樣(大小寫、目錄層級都要一致)。

  1. 從最新 commit 還原
git checkout HEAD -- sub_folder/Deleted.file
  1. 或從特定 commit 還原(用 commit hash)
git checkout <commit_hash> -- sub_folder/Deleted.file

方法三:從 Local Changes 還原

如果檔案還在 Local Changes 裡顯示為已刪除:

  1. 點左側 Local Changes
  2. 找到該檔案
  3. 右鍵 → Discard Changes

常見問題

很久前刪除的檔案,無法從 Fork 快速找到刪除檔案的哪一筆紀錄 commit hash

如果還記得檔案名稱(大小寫要一致,但不清楚放在哪一個目錄):

git log --all --full-history -- "**/Deleted.file"

*** 符號說明:

  1. ** 匹配任意層數目錄(包含零層)
  2. * 只匹配單一層目錄或檔名中的任意字元

不確定路徑深度時建議用 **

如果不確定檔名大小寫,用 grep -i 做大小寫不敏感的搜尋:

git log --all --full-history --name-only --format="" | grep -i "deleted.file"

出現 N 次,代表這個檔案在 GIT 歷史中被修改過 N 次,有很多版本可以還原。找到正確路徑後,再用完整正確路徑去還原。

找到要復原的 commit hash:

git log --all --full-history -- "**/Deleted.file"

為什麼 git show HEAD --name-only | grep Deleted.file 沒有結果?

git show HEAD --name-only 只會列出最新那一筆 commit 有變動的檔案,不是所有檔案,所以沒出現不代表不存在。

可能原因:

  • 這個檔案很久沒被修改,最近的 commit 根本沒動到它
  • 檔案已經被刪除了
  • 路徑不對

先確認檔案存在位置

看它現在存不存在於 working tree:

find . -name "Deleted.file"

看目前 HEAD 裡有沒有這個檔案(不管有沒有被修改):

git ls-files | grep Deleted.file

參考資料