2.3 時光機:撤銷與復原#
Git 最大的價值就是「可以後悔」。三個最常用的撤銷場景:
放棄工作區修改:git restore#
改壞了,想讓檔案回到上次 commit 的狀態:
git restore app.py
⚠️ 警告:這會永久丟棄未提交的修改,救不回來。執行前先確認。
想放棄所有修改:
git restore .
移出暫存區:git restore --staged#
不小心 git add 了不該提交的檔案,把它移出暫存區(檔案內容不會被改掉):
git restore --staged app.py
流程示意:
工作區 ──add──▶ 暫存區 ──commit──▶ 儲存庫
▲ │
└── restore ─────┘ (移出暫存區,檔案還在)
│
└── restore(無參數) (丟棄工作區的修改)
忽略不必要的檔案:.gitignore#
有些檔案永遠不該進版本控制:編譯產物、依賴套件、機密設定、系統垃圾檔。在專案根目錄建立 .gitignore:
# 依賴套件
node_modules/
# 編譯產物
dist/
*.pyc
__pycache__/
# 環境變數與機密
.env
config/secret.yml
# 系統與編輯器檔案
.DS_Store
.idea/
撰寫技巧:
*.pyc:*是萬用字元,忽略所有.pyc檔node_modules/:結尾的/表示忽略整個資料夾#開頭是註解- 每行一條規則
GitHub 上有各語言的現成
.gitignore範本(搜尋 "github gitignore templates"),直接複製來改最快。注意:
.gitignore只對「還沒被追蹤」的檔案有效。如果檔案已經被 commit 過,要先git rm --cached <file>移除追蹤,.gitignore才會生效。