Here we will show you how to track a type of files in a Git repository by writing a proper .gitignore
file.
To check the result of .gitignore
in the following part, we assume you have a newly initiated Git repository with below directory structure.
|-- a.conf
|-- b.h
|-- conf/
| |-- conf.conf
| `-- extra/
| `-- extra.conf
`-- include/
`-- include.h
Track only a type of files
If you want to ignore all the *.conf
files under the whole repository mentioned above, the .gitignore
will as below:
# goal: ignore everything except /conf/**/*.conf
# ignore everything in the root
*.*
# exclude *.conf
!*.conf
Test the .gitignore
with git status
:
$ git status
On branch master
Initial commit
Untracked files:
(use "git add <file>..." to include in what will be committed)
a.conf
conf/
nothing added to commit but untracked files present (use "git add" to track)
As you see, it prompts only a.conf
and conf
folder are untracked, while the include
folder is not mentioned for it does not contain any conf
file but the conf
folder does. This means only the files mentioned being untracked by git status
are expected to be tracked according to the rules inside the .gitignore.
Track only a type of files under a folder
Again take the repository mentioned in the beginning for example, assuming you want to track only *.conf
files under conf
directory as well as its subdirectories. Write the .gitignore
file like this:
# goal: ignore everything except /conf/**/*.conf
# ignore everything in the root
/*
# exclude /conf/
!/conf/
# ignore all files in /conf and its subdirectories
/conf/**/*.*
# exclude *.conf in /conf and its subdirectories
!/conf/**/*.conf
Test the .gitignore
:
$ git status
On branch master
Initial commit
Untracked files:
(use "git add <file>..." to include in what will be committed)
conf/
nothing added to commit but untracked files present (use "git add" to track)
As what is expected, it only prompt the conf
folder is untracked.