How to .gitignore all files/folder in a folder, but not the folder itself?

 

To ignore all files and subfolders within a specific folder in Git, but not the folder itself, you can use the .gitignore file along with a pattern that includes a trailing slash /. This pattern will exclude the contents of the folder while keeping the folder itself in your Git repository. Here's an example:

Let's assume you have a directory structure like this:

my_folder/ ├── file1.txt ├── file2.txt ├── subfolder/ │ ├── file3.txt │ └── file4.txt └── subfolder2/ ├── file5.txt └── file6.txt

You want to ignore all the files and subfolders within the my_folder directory but keep the my_folder itself in the repository.

Create or edit the .gitignore file in the root directory of your Git repository and add the following entry:

my_folder/*

This entry tells Git to ignore all the contents of my_folder, but not the folder itself. The /* at the end of the pattern is what makes this work.

After adding this entry to your .gitignore file, the contents of my_folder will be ignored, and the folder itself will be tracked in your Git repository.

Here's what your .gitignore file might look like:

bash
# Ignore contents of my_folder, but not my_folder itself my_folder/*

With this configuration, the my_folder directory will remain in your Git repository, but any files or subfolders within it will be ignored.

Comments