32

I'm using the following code to ignore all files except for certain filenames and extension

*
!.gitattributes
!.gitignore
!readme.md
!.gitkeep
!*.php

For some reason, its only allowing me to commit the .gitignore and readme.md, even though I have php files in subfolders etc. Is there anything wrong with it? Just fyi, I'm using "git add -A" to pick up the files to commit.

miken32
  • 42,008
  • 16
  • 111
  • 154
jleck
  • 821
  • 1
  • 8
  • 14
  • the answer [here](https://stackoverflow.com/a/50606028/382515) worked for me, adding `!.gitignore` at the end – Ivan Ferrer Villa Mar 04 '20 at 10:04
  • Does this answer your question? [Is there a way to tell git to only include certain files instead of ignoring certain files?](https://stackoverflow.com/questions/1279533/is-there-a-way-to-tell-git-to-only-include-certain-files-instead-of-ignoring-cer) – miken32 Aug 24 '22 at 16:10

2 Answers2

61

The solution is to tell Git not to ignore sub directories:

*
!.gitattributes
!.gitignore
!readme.md
!.gitkeep
!*.php
!*/

Otherwise, only the *.php files in the first directory level will be accepted and all sub directories will be ignored.

eckes
  • 64,417
  • 29
  • 168
  • 201
15

The most sophisticated method to achieve this

create .gitignore file in repository root, and add below lines to .gitignore file

*.*
!.gitattributes
!.gitignore
!readme.md
!.gitkeep
!*.php

this will include all specified file from directory and subdirectory recursively.

tested on

git version 2.12.2.windows.2

Smaranjit
  • 659
  • 7
  • 17
  • 4
    I like this answer better than the accepted one because it works beyond just one level of recursion – Magnus May 22 '17 at 16:53
  • 2
    This approach fails to ignore files with no extension – ojchase May 07 '20 at 21:50
  • @ojchase indeed, but it still solves my personal use-case fully, as I can add appropriate endings if a file pops up that shouldn't be tracked. – xeruf Oct 17 '20 at 16:39