With Git you are able to define file exceptions to exclude certain files and folders from git repository commits. You can create files which contain a list of patterns which git will check against on each git add and ignore any matching files.
You can create ignore pattern lists to ignore files on either a global scale which will affect all repositories on the system or limit it to a specific repository.
Both types of ignore use a .gitignore file which contains literal paths of files inside the repository or patterns which will be used to exclude matching files and directories.
You can skip to the bottom of the post for a few common examples.
.gitignore patterns
Patterns inside the .gitignore file are matched from the root directory of the git repository. Patterns are comprised of a wildcard character *, to match any character, and literal characters to match the exact phrase.
A typical example of using a .gitignore file would be to exclude all files ending in .log. The below pattern would be added to the .gitignore file
*.log
Or, as with something like log4j, your log files may include numbers at the end. This pattern will exclude any file names that contain .log.
*.log*
Another use is to exclude all files in a specific path, such as the application build directory. This will ignore the Build directory and everything within it.
/Build/*
A double asterisk (**) has its own special meaning and represents matching in all directories. For example, a/*/c would only match a single folder between a and b – a/this/b would match but /a/this/and/this/b would not match. Using a double asterisk would match in both scenarios.
/src/**/tmp # exclude any /tmp files or folders at any level in the /src/ folder.
Single repository .gitignore
Add your patterns to the below file to add exclusions to affect only a singe git repository. You must make sure you have changed to the root directory of your repository, or include it in the file path.
vi /path/to/repository/.git/info/exclude
Global .gitignore
You must run a git config command to enable .gitignore to work across all local repositories. You can edit the ~/.gitignore path if required.
git config --global core.excludesfile ~/.gitignore
Once enabled, edit the ~/.gitignore file and add patterns which will affect the next git add command.
vi ~/.gitignore
For example, you may add a global gitignore entry for .bak files. Add the following line to you global gitignore file:
*.bak
You can use just one of the above methods or a combination of both gitignore methods on your git client.
Common .gitignore examples