首頁·終端機命令

git reset

git

用法

git reset [--soft|--mixed|--hard] <commit> | git reset <path>

把分支指標移到別的提交:--soft 讓改動全留在暫存區,--mixed(預設)連暫存區一起清掉但改動還在檔案裡,--hard 連檔案裡的改動也一起丟掉,找不回來。

常用選項

選項含義
--softmove the branch only; index and files keep everything, so the change stays staged
--mixeddefault: also clear the staging area, leaving edits in your files
--hardalso overwrite your files; uncommitted work is destroyed
<path>no commit given: unstage that path
--keepmove but refuse if it would overwrite a local change
--mergelike --hard but keeps changes that do not collide

範例

git reset --soft HEAD~1

undoes the last commit and leaves everything staged

git reset HEAD~1

undoes the last commit; the changes sit in your files, unstaged

git reset src/app.ts

unstages one file without changing it

git reset --hard origin/main

throws away local commits AND uncommitted edits

難的地方在於復原有好幾種:把分支的指向挪走,和補一個反向提交,不是一回事。

怎麼看

  • 方括號 [ ] 表示這部分可以不寫。
  • 省略號 … 表示可以寫多個。
  • 選項區分大小寫——有些命令裡 -r 和 -R 不是一回事。

常見問題

Q. git reset 是做什麼的?

把分支指標移到別的提交:--soft 讓改動全留在暫存區,--mixed(預設)連暫存區一起清掉但改動還在檔案裡,--hard 連檔案裡的改動也一起丟掉,找不回來。

Q. 怎麼寫?

git reset [--soft|--mixed|--hard] <commit> | git reset <path> —— 方括號表示可以省略的部分。

Q. 值得記的選項有幾個?

這裡列了 6 個,完整列表在 man git。這條命令屬於git。

相關命令

man 手冊: man git-reset