14

Repo structure:

.gitignore
file1
file2
dir/
    file3
    <stuff>

I want to ignore everything inside dir except file 3. Here's what I have in my .gitignore file:

dir/*
!dir/file3

But this doesn't seem to work. git still tries to index everything in dir. How do I fix this?

UPDATE - Fixed after deleting the old .gitignore file, and making a new one. The new one was not made using > .gitignore.

Tushar Rakheja
  • 315
  • 1
  • 3
  • 11
  • It is not possible to re-include a file if a parent directory of that file is excluded. [Source](https://git-scm.com/docs/gitignore) – Psytho Sep 12 '16 at 12:50
  • 1
    @Alex.S Yes it is possible, you can `add -f` to force it to be tracked – Cory Kramer Sep 12 '16 at 12:54

2 Answers2

32

The right way to do it is:

!dir
dir/*
!dir/file3

Note that there are other solutions, such as creating a local .gitignore file in dir/, which will take precedence over the previous one.

Curiously, I also tried your solution, and

dir/*
!dir/file3

Seems to work for me. If someone could comment on this, it would be appreciated.

Graham
  • 7,431
  • 18
  • 59
  • 84
MayeulC
  • 1,628
  • 17
  • 24
  • 2
    The second one works because dir/ is not ignored. Only dir content. And you can exclude (un-ignore) a file whose folder is not ignored. – VonC Sep 12 '16 at 13:24
  • I edited that doc back in the days: https://stackoverflow.com/documentation/review/changes/2697. Since then, subsequent edits were... not so accurate. – VonC Sep 12 '16 at 13:27
  • Ok, I have a more accurate picture of what's happening here, then. I might submit an edit in a few hours (~5), but feel free to do so in the mean time. It's a shame that such "vandalism" goes trough. I am sure the editors didn't really mean to add invalid information, but reviewers should probably check it more carefully, at least trying the solutions. I can't say how much I am pissed. Documentation _should_ be accurate, that's what it's for. – MayeulC Sep 12 '16 at 13:53
  • 1
    A few more questions, then: what is your git version? I suppose you are using it from the command line? And did you try putting a .gitignore file in the subdirectory? – MayeulC Sep 13 '16 at 11:16
  • Very sorry for replying so late. The version of git I'm using is 2.9.2.windows.1. Yes, from the command line. I use Powershell. So it does work now. I deleted the .gitignore file and made the same one again, except that I didn't make the new one using `> .gitignore`. – Tushar Rakheja Sep 17 '16 at 10:13
  • 1
    Might be related to line endings, that was one of my ideas. I have no idea how powershell handles those, but I am pretty sure git requires CR and not CRLF, unless explicitly configured to. – MayeulC Sep 17 '16 at 10:27
3

this worked for me:

!/dir/
/dir/*
!/dir/file3
josef
  • 872
  • 9
  • 8