Ignoring files in Git

Ignore files in a git repository

Use .gitignore to allow sharing ignoring rules (version controlled)

If you want some files being untracked in a repository, create an .gitignore file at its root directory and commit it. .gitignore file is used to list all the file patterns to ignore, standard glob patterns work in it.

Basic rules for patterns have been included in below example .gitignore file :

# ignore all .class files
*.class

# exclude lib.class from '*.o', meaning all lib.class are still tracked
!lib.class

# ignore all json files whose name begin with 'temp-'
temp-*.json

# only ignore the build.log file in current directory, not those in its subdirectories
/build.log

# specify a folder with slash in the end
# ignore all files in any directory named temp
temp/

# ignore doc/notes.txt, but not doc/server/arch.txt
bin/*.txt

# ignore all .pdf files in the doc/ directory and any of its subdirectories
# /** matches 0 or more directories
doc/**/*.pdf

Remember to commit it:

$ git add .gitignore
$ git commit 

Note: Adding new patterns in .gitignore won’t affect the files already tracked by Git. You can stop tracking a file.

You can have more than one .gitignore file in subdirectories. Its content will only apply to the folder it resides.

Use .git/info/exclude to only ignore files locally (not version controlled)

If you just want a personal and local ignoring configuration without committing a .gitignore file, use .git/info/exclude to achieve that.

What you do is just adding exclude rules in .git/info/exclude within in the root of a repository.

Any rule added in the file will not be pushed to a remote repository. This way enables you to ignore locally generated files and no need to worry about other users.

Ignore files in all repositories

If you want to ignore some files for all repositories, you can set a global gitignore file. Below is an example to ignore .DS_Store files :

File ~/.gitignore_global :

*~
.*.swp
.DS_Store

Then configure it as your global gitignore settings in Git :

$ git config --global core.excludesfile ~/.gitignore_global

Debug gitignore files

check-ignore command can be used to debug if a file/folder is excluded by some ignoring/exclude rules you’ve set up :

$ git check-ignore -v <pathname>

If the pathname matches an exclude pattern, it outputs the gitignore file, line number, pattern and your query pathname. Otherwise, nothing is output.

Note: By default, tracked files are not output since they are not subject to exclude rules. If a file is tracked before and untracked currently, it can be output.

Below example to debug if user.csv is excluded:

# Debug whether user.csv is exclude by some ignoring rule 
$ git check-ignore -v users.csv
.gitignore:3:*.csv      user.csv

Here user.csv is excluded by *.csv pattern in .gitignore.

Read more: