文件操作与 .gitignore
约 480 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Git › 本地仓库操作(在新窗口打开) › 文件操作与 .gitignore
git rm
# 删除文件并暂存删除操作
git rm old-file.txt
# 等价于 rm old-file.txt + git add old-file.txt
# 从暂存区删除但保留工作区文件(不再跟踪)
git rm --cached config.json
# 递归删除目录
git rm -r old-dir/git mv
# 重命名文件(并暂存操作)
git mv old-name.txt new-name.txt
# 等价于 mv old-name.txt new-name.txt + git rm old-name.txt + git add new-name.txt.gitignore
.gitignore 告诉 Git 哪些文件不要跟踪。
基本语法
# 注释
node_modules/ # 忽略目录
*.log # 忽略所有 .log 文件
!important.log # 但 important.log 不被忽略(取反)
/build/ # 忽略 build 目录及其内容
/config/.env # 忽略特定文件
/vendor/ # 忽略 vendor 目录
*.class # 忽略编译产物
.DS_Store # macOS 系统文件常见模板
# 项目 .gitignore 示例
# --- 依赖 ---
node_modules/
vendor/
.bundle/
# --- 构建产物 ---
dist/
build/
*.js.map
*.d.ts
# --- 环境变量 ---
.env
.env.local
.env.*.local
# --- IDE ---
.vscode/
.idea/
*.swp
*.swo
# --- 操作系统 ---
.DS_Store
Thumbs.db
# --- 日志 ---
*.log
npm-debug.log*仓库内的 .gitignore 与全局的 .gitignore
# 仓库级:随仓库分发,团队成员共用(推荐)
# 放在仓库根目录下
# 全局级:只影响当前开发机,不随仓库分发
git config --global core.excludesFile ~/.gitignore_global已跟踪文件的忽略
如果文件已经被 Git 跟踪,.gitignore 不会生效——需要先 git rm --cached:
# 停止跟踪文件(但保留工作区副本)
git rm --cached config.json
# 然后再写入 .gitignore
echo "config.json" >> .gitignore
git add .gitignore
git commit -m "stop tracking config.json"小结
git rm删除并暂存,git rm --cached停止跟踪但保留文件。git mv重命名并暂存。.gitignore控制哪些文件不纳入 Git 管理,支持*、?、!取反等模式。- 已跟踪的文件忽略需先
git rm --cached。 - 全局
.gitignore通过core.excludesFile配置,适合 IDE 文件、系统文件。
上一节:查看历史(git log) 下一节:分支基础
