When using Git for version control,.gitignore
Files 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..gitignore
How to take effect later.
Scene description
Suppose there is a project root directoryunpackage
Folders, we hope to ignoreunpackage
All files and folders under the folder, but keep theres
Folder. That is to say,unpackage/res/
Need to be tracked by Git, andunpackage/
Other contents under it need to be ignored.
Solution
exist.gitignore
Add the following rules to the file:
unpackage/* !unpackage/res/
Rule explanation:
-
unpackage/*
:neglectunpackage
All files and folders under the folder. -
!unpackage/res/
:Excludeunpackage/res/
Folders, that is, not ignoredres
Folders and their contents.
Revise.gitignore
How to take effect after
If you've been.gitignore
Write 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.gitignore
Rule matching. We need to clear the cache and let Git reapply.gitignore
rule.
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 cacheunpackage
The contents of the folder, but the local files will not be deleted. -
git add .
: Add the file again and apply the new one.gitignore
rule. -
git commit
: Submit changes.
2. Check whether it is effective
Run the following command to checkunpackage
The 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
-
If you have already
unpackage/
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-repo
orBFG Repo-Cleaner
tool. -
if
unpackage/res/
There are subfolders or files that need to be tracked, and Git will automatically track them becauseres
The folder itself is not ignored.
Summarize
Through reasonable configuration.gitignore
Files, 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..gitignore
How to take effect later. Hope this article helps you!