Tushar Rakheja Tushar Rakheja - 2 months ago 12
Git Question

How to ignore everything in a directory except one file

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
.

Answer

As per Exceptions in a .gitignore file, 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.