Skip to content

git復原修改

以下是 Git 各種回復檔案的操作方式,並說明每個操作會影響 workspacestaginglocalremote 中的程式碼。

Git 回復檔案操作總整理

Git 指令 區域影響 說明
git restore <file> workspace workspace 中的檔案回復到 staginglocal 的狀態,撤銷 workspace 中的修改。
git restore --staged <file> staging staging 區域的檔案回復到 workspace 狀態,撤銷 git add 動作,使檔案從 staging 區域移除,但不影響 workspace。
git checkout <file> workspace workspace 中的檔案回復到 local 儲存庫最新的版本,所有未提交的修改會被覆蓋。 (較舊的指令,不推薦,建議使用 git restore)
git reset HEAD <file> staging 將檔案從 staging 區域移除,回復到 workspace 狀態,撤銷 git add,但不會影響檔案本身的內容。
git reset --soft <commit> local local 儲存庫的 HEAD 移回到指定 commit,保留 stagingworkspace 的修改。
git reset --mixed <commit> local, staging local 儲存庫的 HEAD 移回到指定 commit,並清除 staging 區域的修改,但 workspace 中的變更仍保留。
git reset --hard <commit> local, staging, workspace local 儲存庫、stagingworkspace 全部回復到指定 commit 的狀態,所有未提交的修改都會被刪除。 ⚠️ 謹慎使用
git clean -f workspace 移除 workspace 中尚未被追蹤的檔案 (未被 Git 管理的檔案,如新增的檔案),不影響 staging 和 local。
git revert <commit> local 建立一個新的 commit,回復指定 commit 的變更,不影響原本的 commit 紀錄 (比較安全的方式)。
git stash stash workspacestaging 的修改儲存起來並清空 workspacestaging,以便進行其他操作後再取回。
git stash pop workspace, staging 將暫存的修改從 stash 中取回到 workspacestaging,並刪除該暫存。
git stash apply workspace, staging 將暫存的修改從 stash 中取回到 workspacestaging,但不刪除該暫存。

區域說明

  • Workspace:你正在編輯的工作目錄,包含尚未加入 Git 的檔案。
  • Staging (Index):已經被 git add 暫存的檔案,等待被 git commit
  • Local (Repository):本地的 Git 儲存庫,包含所有提交 (commits) 的歷史記錄。
  • Remote (Repository):遠端的 Git 儲存庫,例如 GitHub、GitLab 上的專案。
  • Stash:暫存區域,讓你可以臨時保存還未完成的修改。

常見情境示範

  1. 取消尚未加入 staging 的修改

    git restore <file>
    
    • 影響區域:workspace
    • 作用:還原 workspace 中的檔案到 staging 或 local 的狀態。
  2. 取消已經加入 staging 的檔案

    git restore --staged <file>
    
    • 影響區域:staging
    • 作用:將檔案從 staging 移除,但不影響 workspace。
  3. 取消上一個 git add 動作

    git reset HEAD <file>
    
    • 影響區域:staging
    • 作用:將 staging 中的檔案移除回 workspace。
  4. 強制回復到上一次的 commit (⚠️ 謹慎使用):

    git reset --hard HEAD
    
    • 影響區域:local, staging, workspace
    • 作用:刪除 staging 和 workspace 中的所有修改,並回復到最後一次的 commit。
  5. 撤銷一個特定的 commit

    git revert <commit-hash>
    
    • 影響區域:local
    • 作用:建立一個新 commit,回復該 commit 的修改,而不刪除原本的 commit 紀錄。

選擇正確的回復方式

  • 僅撤銷尚未加入的修改git restore
  • 撤銷已經加入 staging 的檔案git restore --staged
  • 回復到舊的 commit 且保留修改git reset --soft
  • 刪除 staging 的變更但保留 workspacegit reset --mixed
  • 清空所有修改並回到特定版本git reset --hard
  • 安全地回復特定 commitgit revert
  • 臨時保存並清空工作區git stash