git ignore all files except one extension and folder structure

GitGitignore

Git Problem Overview


This is my .gitignore:

#ignore all kind of files
*
#except php files
!*.php

All I want is to ignore all kind of files except the .php ones, but with this .gitignore I'm also ignoring folders...

Is there a way to tell git to accept my project folder structure while keeping the track only of the .php files?

It seems like now I can't add folders to my repo:

vivo@vivoPC:~/workspace/motor$ git add my_folder/
The following paths are ignored by one of your .gitignore files:
my_folder
Use -f if you really want to add them.
fatal: no files added

Git Solutions


Solution 1 - Git

This is simple, just add another entry !my_folder in your .gitignore

#ignore all kind of files
*
#except php files
!*.php
!my_folder

The last line will take special care of my_folder, and will not ignore any php files within it; but files within other folders will still be ignored because of the first pattern of *.

EDIT

I think I misread your question. If you want to ignore all files except .php files, you can use

#ignore all kind of files
*.*
#except php files
!*.php

This will not ignore any file which doesn't have an extension (example: if you have README and not README.txt ), and will ignore any folder with a . in its name (example: directory named module.1).

FWIW, git doesn't track directories, and hence there is no way to specify ignore rules for directory vs file

Solution 2 - Git

I had a similar problem; I wanted to whitelist *.c, but the accepted answer didn't work for me, because I had files that didn't contain ".".

So for those who want to handle that:

# ignore everything
*

# but don't ignore files ending with slash = directories
!*/

# and don't ignore files ending with ".php"
!*.php

Solution 3 - Git

This works for me (excludes all imgs folder content except .gitkeep files)

/imgs/**/*.*
!/imgs/**/.gitkeep

Solution 4 - Git

Note that if the ! has no effect, you probably excluded a folder. From the docs (emphasis mine):

> An optional prefix "!" which negates the pattern; any matching file > excluded by a previous pattern will become included again. It is not > possible to re-include a file if a parent directory of that file is > excluded. Git doesn’t list excluded directories for performance > reasons, so any patterns on contained files have no effect, no matter > where they are defined.

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
Questionjavier_domenechView Question on Stackoverflow
Solution 1 - GitAnshul GoyalView Answer on Stackoverflow
Solution 2 - GitkalnarView Answer on Stackoverflow
Solution 3 - GitmazzView Answer on Stackoverflow
Solution 4 - GitRoaldView Answer on Stackoverflow