文件狀態分類
Git 中的文件有以下幾種狀態:
工作區文件狀態:
├── 未跟蹤 (Untracked)
├── 已跟蹤 (Tracked)├── 未修改 (Unmodified) ├── 已修改未暫存 (Modified/Unstaged)└── 已暫存 (Staged)
1. 未跟蹤 (Untracked)
定義:Git 完全不知道這個文件的存在
特點:
- 新創建的文件
- 從未被
git add
過 - 不在 Git 的版本控制范圍內
- Git 不會自動備份或恢復這些文件
示例:
# 創建一個新文件
echo "hello" > newfile.txt# 查看狀態
git status
# 輸出:
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
# newfile.txt
2. 未暫存 (Unstaged/Modified)
定義:文件已被 Git 跟蹤,但當前的修改還沒有添加到暫存區
特點:
- 文件之前已經被
git add
或git commit
過 - 文件內容發生了變化
- 變化還沒有通過
git add
添加到暫存區 - Git 知道這個文件,也知道它被修改了
示例:
# 修改一個已存在的文件
echo "modified content" > existingfile.txt# 查看狀態
git status
# 輸出:
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git restore <file>..." to discard changes in working directory)
# modified: existingfile.txt
實際演示對比
# 初始狀態
git status
# On branch main
# nothing to commit, working tree clean# 1. 創建新文件 (未跟蹤)
echo "new file" > untracked.txt# 2. 修改已存在的文件 (未暫存)
echo "modified" > README.mdgit status
# On branch main
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git restore <file>..." to discard changes in working directory)
# modified: README.md ← 未暫存 (已跟蹤但有修改)
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
# untracked.txt ← 未跟蹤 (Git不知道這個文件)
不同的清理命令
處理未跟蹤文件
# 只刪除未跟蹤的文件
git clean -f# 刪除未跟蹤的文件和目錄
git clean -fd# 預覽會刪除哪些未跟蹤文件
git clean -n
處理未暫存的修改
# 丟棄未暫存的修改 (恢復到最后一次commit的狀態)
git checkout .
# 或
git restore .# 丟棄特定文件的未暫存修改
git checkout -- filename
# 或
git restore filename
一次性處理兩種情況
# 丟棄所有修改 + 刪除未跟蹤文件
git reset --hard HEAD # 處理未暫存修改
git clean -fd # 處理未跟蹤文件
狀態轉換圖
[未跟蹤文件] ↓ git add
[已暫存文件]↓ git commit
[已提交文件] → 修改內容 → [未暫存修改]↑ ↓ git add└─────── git commit ←── [已暫存修改]
實際場景舉例
# 場景1:開發新功能
touch feature.js # 創建新文件 → 未跟蹤
vim README.md # 修改已有文件 → 未暫存# 場景2:查看不同類型的修改
git status
# Changes not staged for commit: ← 這些是未暫存修改
# modified: README.md
#
# Untracked files: ← 這些是未跟蹤文件
# feature.js# 場景3:分別處理
git add feature.js # 未跟蹤 → 已暫存
git restore README.md # 未暫存修改 → 丟棄修改
git clean -f # 刪除其他未跟蹤文件
總結對比
特征 | 未跟蹤 (Untracked) | 未暫存 (Unstaged) |
---|---|---|
Git是否知道文件 | ? 不知道 | ? 知道 |
文件是否存在歷史版本 | ? 沒有 | ? 有 |
是否可以用 git restore 恢復 | ? 不能 | ? 能 |
是否會在 git diff 中顯示 | ? 不會 | ? 會 |
清理命令 | git clean | git restore 或 git checkout |
風險程度 | 刪除就徹底沒了 | 可以恢復到最后commit狀態 |
記憶技巧:
- 未跟蹤 = Git 不認識這個文件
- 未暫存 = Git 認識文件,但修改還沒準備好提交