Skip to content

📁 第五章:文件状态详解 —— Git 的"生命周期"

文件的四种状态

在 Git 的世界里,每个文件都有四种可能的状态,就像一个人的一天——

text
┌──────────┐     git add      ┌──────────┐    git commit   ┌──────────┐
  │ Untracked │ ──────────────→  │ Staged   │ ─────────────→  │Committed │
  │ (未跟踪)  │                  │ (已暂存)  │                 │ (已提交)  │
  └──────────┘                  └──────────┘                 └──────────┘
       ↑                            │                              │
       │         修改文件            │                              │
       │    ┌───────────────────────┘                              │
       │    │                                                      │
       │    ▼                                                      │
       │  ┌──────────┐          修改已提交的文件                    │
       │  │ Modified  │ ←──────────────────────────────────────────┘
       │  │ (已修改)  │
       │  └──────────┘
       │       │
       │       │ git restore / git checkout
       │       ▼
       │    (丢弃修改)

       │  git rm --cached
       └────────────────────  (变为未跟踪)
状态含义生活类比
Untracked新文件,Git 还不知道它的存在桌上新买的水果,还没放进冰箱
Modified已跟踪的文件被修改了冰箱里的菜被拿出来改了配方
Staged修改已放入暂存区,等待提交菜装盘了,就等端上桌
Committed安全保存在 Git 数据库中成品入库,有存档了

实战演示:文件状态的变化

bash
# 场景:小明在开发"我的第一个网站"

# 1. 创建一个新文件 —— Untracked
echo 'body { color: blue; }' > style.css
git status
On branch main
Untracked files:
  (use "git add <file>..." to include in what will be committed)
        style.css
nothing added to commit but untracked files present

# 2. 添加到暂存区 —— Staged
git add style.css
git status
On branch main
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   style.css

# 3. 提交 —— Committed
git commit -m "feat: 添加基础样式"
[main b2c3d4e] feat: 添加基础样式
 1 file changed, 1 insertion(+)
 create mode 100644 style.css

# 4. 修改已提交的文件 —— Modified
echo 'body { color: red; font-size: 16px; }' > style.css
git 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:   style.css

.gitignore—— 告诉 Git "别管这些"

有些文件你不想让 Git 跟踪,比如编译产物、日志文件、密码配置等。这时候就需要 .gitignore 文件。

bash
# 创建 .gitignore 文件
cat > .gitignore << 'EOF'
# 依赖目录
node_modules/
vendor/

# 编译产物
dist/
build/
*.o
*.pyc

# 日志
*.log
logs/

# 操作系统文件
.DS_Store
Thumbs.db

# IDE 文件
.vscode/
.idea/
*.swp

# 环境变量(密码什么的千万别提交!)
.env
.env.local
EOF

⚠️ 注意: 这里有个大坑,我当年踩过——如果你的文件已经被 Git 跟踪了,再把它加到.gitignore是无效的!你需要先从 Git 的跟踪中移除:git rm --cached <file>。特别是.env文件,如果意外提交了密码,就算后面删除了,历史记录里还能找到。永远在项目一开始就创建 .gitignore!