How to I add something to the .gitignore so that the match is not recursive?

GitIgnoreGitignore

Git Problem Overview


How to I add something to the .gitignore so that the match is not recursive?

For example, I wish to ignore the directory foo and the file bar.txt in the current directory, but not any that exist in subdirectories.

I have tried this for my .gitignore file:

foo/
bar.txt

But unfortunately git applies this recursively, so that otherdir/bar.txt and otherdir/foo/ also get ignored, which is not what I want.

(Is there a command in git that shows me all ignored files, and reference the .gitignore file that is responsible for the file being ignored? This would be useful for debugging.)

Git Solutions


Solution 1 - Git

The solution is to place a leading slash on the .gitignore entries:

/foo/
/bar.txt

(I thought I tried this before posting on StackOverflow, but clearly I hadn't tried it properly, as this works perfectly.)

Solution 2 - Git

From the gitignore manpage:

> An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

So !* as the first line in your .gitignore will clear all previous patterns.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpauldooView Question on Stackoverflow
Solution 1 - GitpauldooView Answer on Stackoverflow
Solution 2 - GithermannlooseView Answer on Stackoverflow