6.2 常見錯誤情境與一句話解決方案
提交相關
| 情境 | 解法 |
| commit 訊息打錯字(還沒 push) | git commit --amend -m "正確訊息" |
| commit 漏了檔案(還沒 push) | git add 檔案 後 git commit --amend --no-edit |
| 不小心 add 了不該加的檔案 | git restore --staged <file> |
| 不小心 commit 了機密檔案 | git rm --cached <file> 移除追蹤,並立刻更換該機密 |
修改與後悔
| 情境 | 解法 |
| 改壞了想回到上次 commit | git restore <file> |
| 想放棄所有未提交修改 | git restore . |
| merge 到一半想放棄 | git merge --abort |
| 誤刪分支或 reset 過頭 | git reflog 找到位置後 git reset --hard <hash> 或 git branch <name> <hash> |
分支與遠端
| 情境 | 解法 |
| push 被拒絕(fetch first) | 先 git pull 再 git push |
| 想放棄整條功能分支 | git branch -D <branch> |
| 遠端分支已在 GitHub 刪除但本地還看到 | git fetch --prune |
| clone 錯分支,想要別的分支 | git switch <branch>(clone 後所有分支都在本地) |
衝突
| 情境 | 解法 |
| merge 衝突 | 編輯衝突檔案 → git add → git commit |
| cherry-pick 衝突 | 編輯檔案 → git add → git cherry-pick --continue |
| 想看衝突的兩邊原始版本 | git diff 或直接看檔案中 <<<<<<< / >>>>>>> 標記 |
暫存
| 情境 | 解法 |
| 寫到一半要切分支 | git stash → 切走 → 回來後 git stash pop |
| 收了 stash 忘了有什麼 | git stash list |
.gitignore 沒生效 | 檔案已被追蹤:git rm --cached <file> 後再 commit |
終極保險:任何操作搞砸了,先 git status 和 git reflog 看清楚狀況,再決定下一步。不要在慌亂中連續下指令。