How to Ignore Everything in a Folder except Specific File(s) in GIT

gitignore all except one file

Sometimes it might be required to ignore everything in a folder except specific file(s).

For anyone working with git, they would be familiar with the .gitignore file located at the base folder. GIT uses this file to decide, which files/folders to exclude from the source-control.

Examples are:
1. node_modules/
2. cache folders
3. or any specific file or folder

Let’s consider you have a folder structure like

- config/
- - other/
- - basic.config.ts
- - temp.config.ts
- assets/
- my-app.file.ts
- some-other.file.ts

The above GIT project consists of the following structure:

  1. At the top level, there is a .gitignore file, index.html & style.css
  2. The top level also contains a folder named app, which has subfolders named config/ and assets/
  3. The config folder in turn contains a folder named other/ which can have additional files
  4. It also has 2 files named basic.config.ts and temp.config.ts

For the above scenario, lets consider you want to add all the files/folders to git, except the config folder. For this, one would add the following line of code to the .gitignore file:


This would make sure that all the app/config/ folder, as well as all the files inside it are ignored, and not committed to the GIT repository.

Sometimes it might be required that you need only one or two files/folders and want the others to be ignored. In this scenario, while it might be possible to add all the files/folders in the .gitignore file except the ones that you require.

This process might work for the above scenario, where you have a handful of items. But what happens when you have tens or hundreds of files/folders that you might want to ignore! So many lines just to keep 1 or 2 files in the source control system.

Here we can use the optional ! which negates any previous pattern defined. If the defined pattern matches, it will negate any lower precedence patterns.

So for the above case, if you want to ignore the whole folder, but keep the app/config/basic.config.ts file, then you can put the following in the .gitignore file and you should be good to go.


This will make sure that you ignore everything in a folder except the specific mentioned with the ! command.

You can read more on git here.

Leave a Reply

Your email address will not be published. Required fields are marked *