git add 與 git status
git add 把檔案加到暫存區,git status 查看目前的狀態。這兩個是最常用的 Git 指令。
git status - 查看狀態
git status 讓你知道目前 repository 的狀態:哪些檔案被修改、哪些準備要 commit。
基本用法
git status
輸出範例:
On branch main
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
modified: index.html
Untracked files:
(use "git add <file>..." to include in what will be committed)
style.css
no changes added to commit (use "git add" and/or "git commit -a")
這告訴你:
- 目前在
main分支 index.html被修改了但還沒加到暫存區style.css是新檔案,還沒被追蹤
簡短輸出
git status -s
# 或
git status --short
輸出範例:
M index.html
?? style.css
符號說明:
??- 未追蹤的新檔案M- 被修改的檔案A- 新增到暫存區的檔案D- 被刪除的檔案R- 被重新命名的檔案
左邊的欄位表示暫存區狀態,右邊表示工作目錄狀態:
MM file.txt # 暫存後又被修改
A file.txt # 新增到暫存區
M file.txt # 被修改但未暫存
?? file.txt # 未追蹤
git add - 加入暫存區
git add 把檔案加到暫存區,準備下次 commit。
加入單一檔案
git add index.html
加入多個檔案
git add index.html style.css script.js
加入所有變更
# 加入所有變更(包含新檔案、修改、刪除)
git add .
# 或
git add --all
git add -A
加入特定類型的檔案
# 所有 .js 檔案
git add *.js
# src 目錄下所有檔案
git add src/
# 所有 .css 和 .html 檔案
git add *.css *.html
互動式加入
git add -i
# 或
git add --interactive
這會開啟互動式介面,讓你選擇要加入哪些檔案。
只加入已追蹤檔案的變更
git add -u
# 或
git add --update
這只會加入已經被 Git 追蹤的檔案的修改和刪除,不會加入新檔案。
部分加入(Patch 模式)
如果一個檔案有多處修改,但你只想 commit 其中一部分:
git add -p index.html
# 或
git add --patch index.html
Git 會顯示每一塊修改(hunk),讓你決定要加入哪些:
Stage this hunk [y,n,q,a,d,s,e,?]?
y- 加入這塊n- 不加入這塊q- 離開s- 分割成更小的塊e- 手動編輯
取消暫存
如果不小心 add 錯了,可以用以下指令取消:
# 取消暫存單一檔案
git restore --staged index.html
# 取消暫存所有檔案
git restore --staged .
# 舊版 Git 用法(仍然可用)
git reset HEAD index.html
實際工作流程
# 1. 查看目前狀態
git status
# 2. 修改一些檔案...
# 3. 再次查看狀態
git status
# 4. 加入要 commit 的檔案
git add index.html style.css
# 5. 確認暫存區內容
git status
# 6. 提交
git commit -m "Update styles"
.gitignore 的影響
如果檔案符合 .gitignore 的規則,git add 會忽略它:
# 假設 .gitignore 包含 node_modules/
git add node_modules/ # 不會有任何效果
如果你確實要加入被忽略的檔案:
git add -f node_modules/file.js
# 或
git add --force node_modules/file.js
常用組合技
查看變更後一次加入並 commit
git status
git add .
git commit -m "Your message"
加入所有變更並 commit(不含新檔案)
git commit -am "Your message"
這等同於 git add -u 加上 git commit -m,但只對已追蹤的檔案有效。
查看即將 commit 的內容
# 查看暫存區和上次 commit 的差異
git diff --staged
# 或
git diff --cached
小技巧
空目錄
Git 不追蹤空目錄。如果你需要保留空目錄,可以在裡面放一個 .gitkeep 檔案:
mkdir logs
touch logs/.gitkeep
git add logs/.gitkeep
查看會被加入的檔案
在 git add 之前,可以先看看會加入哪些檔案:
git add --dry-run .
# 或
git add -n .