Home > database >  Why is gitignore ignoring all my files despite writing only one file to be ignored?
Why is gitignore ignoring all my files despite writing only one file to be ignored?

Time:12-28

I created a gitignore in the root of my project folder like this:

*

!src/
!.gitignore

And in my src folder, I have 2 files and a file I want to keep in the local folder but exclude from the repository (3 files in total). So I created another gitignore file in the src folder like this:

file.txt

The command line:

git add .
git commit -m "message"
git push

When I went to my repo, it indeed excluded everything but the src folder and the gitignore file, but in the src folder in the repo, I found only the gitignore file and not the other files.

CodePudding user response:

Your top-level .gitignore file has the rule:

*

This matches all files in all folders at all times. So any file anywhere is ignored, unless otherwise specified.

To fix this, use the "anchor" concept: tell Git that * in the top level should only apply at the top level, i.e.:

/*

Now only top-level files are ignored (and any folders are not searched either, unless overridden, e.g., as by your !src/ line).

(Note that the:

!.gitignore

rule in the top level file means that all .gitignore files everywhere are not-ignored, unless overridden by a more-local rule, but that's probably what you want anyway. Still, you could anchor that rule too, if you wanted.)

  • Related