跳轉至

建立 2024-01-01 更新 2026-09-19

復原修改

「復原」在 Git 裡有很多種,差在動到哪個區域。選錯指令可能把還沒提交的工作刪光,先看表再動手。

指令與影響區域

Git 指令 區域影響 說明
git restore <file> workspace 工作區該檔回到暫存區/最後一次 commit 的內容
git restore --staged <file> staging 取消 git add,檔案內容仍在工作區
git checkout -- <file> workspace 舊寫法,建議改用 git restore(原因見 分支操作)
git reset HEAD <file> staging 與 restore --staged 類似
git reset --soft <commit> local 移動 HEAD,暫存與工作區保留
git reset --mixed <commit> local, staging 移動 HEAD,變更回到工作區
git reset --hard <commit> local, staging, workspace 全部回到該 commit,未提交修改會沒有
git clean -f workspace 刪除未追蹤檔,無法從 Git 救回
git revert <commit> local 新 commit 抵銷舊變更,較安全
git stash stash 把工作區與暫存區收進暫存堆
git stash pop workspace, staging 取出並刪除該筆 stash
git stash apply workspace, staging 取出但保留 stash

區域說明

  • Workspace:正在編的檔。
  • Staging:已 add、等 commit。
  • Local:本機歷史。
  • Remote:GitHub 等遠端。
  • Stash:臨時抽屜,不是正式歷史。

常見情境

取消尚未暫存的修改:

git restore <file>

取消已經 add 的檔(檔案還在):

git restore --staged <file>

放棄工作區與暫存區、回到最後一次 commit(⚠️ 改到的內容會沒有):

git reset --hard HEAD

安全地抵銷某次已提交的變更:

git revert <commit-hash>

怎麼選

  • 還沒 add → git restore
  • 已經 add、還沒 commit → git restore --staged
  • 想暫時切走做別的事 → git stash
  • 已 commit 且可能已 push → git revert
  • 只有自己的本地實驗要整段丟掉 → 才考慮 git reset --hard