logo

Ignoring all files in a specific folder except for one in Git

January 31, 2024

In Git, you can ignore files and folders using the .gitignore file. If the file does not exist in our GitHub repository, you have to create it at the root of our project.

The .gitignore file supports patterns that are matched against file and folder names to determine whether or not they should be ignored.

Here’s how you can do it:

  1. Create a .gitignore file in the root folder of your Git repository if it doesn’t already exist.
  2. To ignore all files in a specific folder, you would add a line like this: path/to/folder/**.

For example, if your project structure looks like this:

└───📁 netlify/
    └───📁 functions/
        └───📁 search/
            ├───📁 src/
            │   └───...
            ├───📄 eleventy-app-config-modules.js
            ├───📄 eleventy-app-dirdata-modules.js
            ├───📄 eleventy-app-globaldata-modules.js
            ├───📄 eleventy-bundler-modules.js
            ├───📄 eleventy-serverless-map.json
            ├───📄 eleventy-serverless.json
            ├───📄 eleventy.config.js
            └───📄 index.js

If you want to ignore all the files and folders within the netlify/functions/search, you would use the below pattern:

netlify/functions/search/**
  • netlify/functions/search/: This targets the search folder inside the functions folder inside the netlify folder, relative to the location of the .gitignore file.
  • **: It’s a special pattern in Git; when used in the .gitignore file, it matches zero or more folders, but in the context of a file path, ** will match any level of nested folders.

In our example from above, the pattern will ignore all files and directories within the netlify/functions/search/ folder, including all levels of subdirectories and their files.

  1. To make an exception and not ignore a specific file in the same folder, you will add the !, which negates the pattern that follows after it. For example, if you want not to ignore netlify/functions/search/index.js, you would add:
!netlify/functions/search/index.js

Your final .gitignore file would look something like this:

# Ignore everything in the `search` folder
netlify/functions/search/**

# But do not ignore this file inside of it
!netlify/functions/search/index.js