1. 创建或编辑 .gitignore 文件

在项目根目录下创建或编辑名为 .gitignore 的文件(如果没有的话):

touch .gitignore  # 如果文件不存在则创建

2. 添加要忽略的文件路径

在 .gitignore 文件中,按行写入需要忽略的文件或目录的路径。例如:

# 忽略根目录下的 example.txtexample.txt 
# 忽略 data 目录下的 temp.logdata/temp.log 
# 忽略所有 .log 文件*.log # 忽略 build 目录build/

3. 处理已跟踪的文件(如果文件已被Git跟踪)

如果文件已经被Git跟踪(即之前提交过),需要先取消跟踪:

git rm --cached <file_path>  # 例如 git rm --cached example.txt

4. 提交 .gitignore 文件

将 .gitignore 文件提交到仓库,使规则生效:

git add .gitignoregit commit -m "Update .gitignore to exclude specific files"

常见场景示例

  • 忽略特定文件config.env
  • 忽略目录node_modules/
  • 忽略所有日志文件*.log
  • 忽略特定后缀文件*.tmp

验证忽略规则

运行以下命令检查文件是否被正确忽略:

git status --ignored

通过以上步骤,目标文件将不再被Git跟踪或提示为未跟踪文件。