Gitignore配置求助:如何忽略所有内容仅保留指定3个文件
Hey there! I’ve run into this exact scenario before—trying to ignore everything except a handful of specific files can feel tricky at first, but the solution is straightforward once you get the hang of Git’s ignore rules.
Here’s the correct .gitignore setup you need:
# Ignore all files and directories by default * # Unignore the files you want to keep !.gitignore !README.md !main.c
Why this works:
Git’s .gitignore uses negation patterns (!) to override earlier ignore rules. By starting with *, we tell Git to ignore every single thing in the directory. Then, each ! line explicitly tells Git "wait, don’t ignore this specific file."
Important notes if your files are in subdirectories:
If, for example, main.c lives inside a src/ folder, you’ll need to adjust the rules to first unignore the directory (otherwise Git won’t look inside it to find the file):
* !.gitignore !README.md !src/ !src/main.c
Quick troubleshooting tips:
- Double-check for conflicting rules in your
.gitignore(like other lines that might be accidentally ignoring these files). - If you’ve already tracked files that should be ignored, run
git rm --cached <filename>to remove them from Git’s tracking without deleting them locally, then commit the change.
内容的提问来源于stack exchange,提问作者L Ja

