We don’t always want Git to track everything in our projects, whether it’s compiled source code, files containing passwords, or temporary files created by editors. Typically, excluding items from version control is a cumbersome task, but not with Git! By using the .gitignore file along with some additional options, we can easily set up project-specific and user-specific ignores.

The simplest and most straightforward approach is to create a .gitignore file in the root directory of your project. The rules specified in this file apply to all directories in your project, unless they contain their own .gitignore file. This centralized approach makes it easy to manage ignores compared to SVN’s svn:ignore, which must be set on every folder. Additionally, the .gitignore file itself can be versioned, which is advantageous.

Here’s an example of a basic .gitignore file:

$ cat .gitignore

Ignore specific files

.DS_Store

Use wildcards as well

*~
*.swp

Ignore all directories and files in a directory

tmp/*/

Of course, .gitignore rules can become more complex. You can also add exceptions to ignore rules by prefixing the line with !. For more advanced usage, refer to the GitHub guide on ignores.

Two important things to note about ignoring files: Firstly, if a file is already being tracked by Git, adding it to .gitignore won’t stop Git from tracking it. You’ll need to use git rm –cached to keep the file in your working tree and then ignore it. Secondly, Git does not track empty directories. If you want them to be tracked, they need to contain something. Typically, creating a .gitignore file within the empty directory is sufficient.

Another option for ignoring files is to edit the $GIT_DIR/info/exclude file ($GIT_DIR usually refers to your .git folder) for project-specific ignores. However, changes made here are not checked into version control, so use this option only for personal files that don’t need to be shared with others working on the same project.

Your final option for ignoring files is to set up a per-user ignore by configuring the core.excludesfile option in your Git config file. You can achieve this by creating a .gitignore file in your HOME directory that will affect all your repositories. Use the following command:

git config –global core.excludesfile ~/.gitignore

For more details on how ignore rules work, refer to the Git manpage. And as always, if you have other tips related to ignoring files, feel free to share them in the comments.