Git ignore everything in a folder except some files

Git allows you to ignore files from version control using a file named .gitignore. There can be various cases where you would like to ignore almost everything in a folder, except a few files.

This could be the case when you would like to exclude everything in the current folder, but commit the .gitignore file, otherwise the next time you clone the repo, Git won’t know what you have excluded.


We need to use the * (star) operator to ignore everything, and then the ! (exclamation mark) operator to remove the exclusion from those files that you would like to keep.

This short quote from the documentation of gitignore describes the use of the ! operator.

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.

So, in our case we’ll have to use something like the following

# Ignore everything

# But not these files