7.1. Creating a .gitignore file for your repository
Git can be configured to ignore certain files and directories. This is configured in a.gitignore
file.
This file can be in any directory and can contain patterns for
files.
You can use certain wildcards in this file.
*
matches several characters.
The
?
parameter
matches one character. More patterns are possible and
described under the following URL:
gitignore manpage
For example, the following
.gitignore
file tells Git to ignore the
bin
and
target
directories and all files ending with a ~.
# ignore all bin directories # matches "bin" in any subfolder bin/ # ignore all target directories target/ # ignore all files ending with ~ *~
You can create the
.gitignore
file
in the root directory of the working tree to make it specific for
the Git repository.
Note
Files that are committed to the Git repository are not automatically removed if you add them to a.gitignore
file. You can use the
git rm -r --cached [filename]
command
to remove existing files from a Git repository.
Tip
The.gitignore
file tells Git to ignore the specified files in Git
commands.
You can
still add ignored files to the
staging area
of the Git repository
by using the
--force
parameter, i.e. with the
git add --force [filename]
command.
This is useful if you want to add, for example, auto-generated binaries, but you need to have a fine control about the version which is added and want to exclude them from the normal workflow.
You can also setup a global
The local
.gitignore
file valid for all Git repositories via the
core.excludesfile
setting. The setup of this setting is demonstrated in the following
code snippet.
# Create a ~/.gitignore in your user directory cd ~/ touch .gitignore # Exclude bin and .metadata directories echo "bin" >> .gitignore echo ".metadata" >> .gitignore echo "*~" >> .gitignore echo "target/" >> .gitignore # Configure Git to use this file # as global .gitignore git config --global core.excludesfile ~/.gitignore
The local
.gitignore
file can be committed into the Git repository and
therefore is visible
to everyone who clones the repository. The
global
.gitignore
file is only
locally visible.