Location>code7788 >text

How to properly configure .gitignore to ignore files under a specific folder (except for a specified subfolder)

Popularity:853 ℃/2025-02-13 15:14:13

When using Git for version control,.gitignoreFiles are a very useful tool that can help us ignore files or folders that do not need to be tracked. However, sometimes we need to ignore everything under a folder, but keep a subfolder in it. This article will introduce in detail how to achieve this requirement and solve the modification..gitignoreHow to take effect later.

Scene description

Suppose there is a project root directoryunpackageFolders, we hope to ignoreunpackageAll files and folders under the folder, but keep theresFolder. That is to say,unpackage/res/Need to be tracked by Git, andunpackage/Other contents under it need to be ignored.

 

Solution

exist.gitignoreAdd the following rules to the file:

unpackage/*
!unpackage/res/

 

Rule explanation:

  1. unpackage/*:neglectunpackageAll files and folders under the folder.

  2. !unpackage/res/:Excludeunpackage/res/Folders, that is, not ignoredresFolders and their contents.


Revise.gitignoreHow to take effect after

If you've been.gitignoreWrite in the fileunpackage/*, After modifying it to the above rules, you need to perform the following steps to make the changes take effect:

1. Clear the Git cache

Git caches the tracked files, even if they are now.gitignoreRule matching. We need to clear the cache and let Git reapply.gitignorerule.

Run the following command:

git rm -r --cached unpackage/
git add .
git commit -m "Update .gitignore to exclude unpackage except res"

Command explanation:

  • git rm -r --cached unpackage/: Remove from Git cacheunpackageThe contents of the folder, but the local files will not be deleted.

  • git add .: Add the file again and apply the new one.gitignorerule.

  • git commit: Submit changes.

2. Check whether it is effective

Run the following command to checkunpackageThe status of the folder:

git status

You should see:

  • unpackage/res/Being followed.

  • unpackage/Other files or folders under   are ignored.

3. Push changes (if required)

If you also need these changes in a remote repository, remember to push:

git push origin <branch-name>

Things to note

  1. If you have alreadyunpackage/The files under   are submitted to the Git repository and these files will be retained in Git history. If you need to completely delete it from history, you can usegit filter-repoorBFG Repo-Cleanertool.

  2. ifunpackage/res/There are subfolders or files that need to be tracked, and Git will automatically track them becauseresThe folder itself is not ignored.


Summarize

Through reasonable configuration.gitignoreFiles, we can flexibly control files and folders tracked by Git. This article introduces how to ignore all contents in a folder, but retain the specified subfolders in it, and resolves the modification..gitignoreHow to take effect later. Hope this article helps you!