乐闻世界logo
搜索文章和话题

How to ignore certain files in Git

1个答案

1

To ignore certain files or folders in Git, you can use the .gitignore file. Here are detailed steps and examples:

  1. Create the .gitignore file Create a .gitignore file in the root directory of your Git repository. If one already exists, simply edit it.

  2. Edit the .gitignore file Open the .gitignore file and add rules to specify which files or folders to ignore. Each line represents a rule.

  3. .gitignore rules examples

    • Ignore all .log files: *.log
    • Ignore a specific file: /todo.txt (ignores todo.txt in the root directory)
    • Ignore a specific folder: temp/ (ignores the temp folder and its contents)
    • Ignore all files except a specific one: /* (ignores all files) and !/README.md (excludes README.md from being ignored)
    • Ignore specific files in nested folders: build/logs/ (ignores all files in the logs folder within the build folder)
    • Ignore all folders except a specific one: /* (ignores all top-level folders) and !/keep-this-folder/ (preserves the keep-this-folder folder)
  4. Commit the .gitignore file to the repository Add and commit the .gitignore file using the following command:

    sh
    git add .gitignore git commit -m "Add .gitignore file"
  5. Check ignored files To view which files are currently ignored by .gitignore, use the following command:

    sh
    git status --ignored
  6. Exception rules If you have already ignored certain files in .gitignore but need to track a specific file, use the ! prefix to specify it.

    Note: If you have manually tracked files that are specified to be ignored in .gitignore, they will not be automatically ignored. In this case, you need to remove them from the Git repository but keep their local copies. Use the following command:

    sh
    git rm --cached FILENAME

    After this, these files will be ignored by .gitignore.

This is how to ignore files in Git. It is very useful for preventing sensitive data, compiled outputs, log files, and other content that should not be committed to version control from being included.

2024年6月29日 12:07 回复

你的答案