How to ignore unwanted files?​

Why to ignore files?

A project’s working directory often contains a number of files you’d rather not save in your repository and share with others.

Some examples of these might be:

  • Files automatically generated by your operating system.

  • Compiled assets created by your build process (e.g. WebPack, Grunt or Gulp).

  • Config files containing sensitive things like API keys or database credentials.

  • Logs or error reports generated by command line tools.

  • Third-party code installed via npm package managers (e.g. node_modules).

  • Third-party code installed via composer (e.g. vendors).

You can exclude these files by not adding them to the staging area when you commit however it’s easy to forget to do that, and the files still be displayed when you run git status.

Creating an ignore file

To avoid having to ignore unwanted files manually, you can create a .gitignore file in the working directory of your project. Inside this file, you can specify simple patterns that Git will use to determine whether or not a file should be ignored.

Ignoring files

Let’s say you have the following directory tree:

├── README
├── config.env
├── foo
|   |── config.env
       └── bar.php
└── index.php

If you wanted to ignore all the config.env files, you just need to enter:

config.env

With this pattern, both of these files would be ignored:

config.env
foo/config.env

To just ignore the config.env in the root directory, you can prefix the pattern with a forward slash, just like this:

/config.env

Want to ignore all of the PHP files in your project? This pattern will do that for you:

*.php

Ignoring folders

The process for ignoring folders is very similar. Just enter the name of the folder:

vendors

With this pattern, Git won’t just ignore vendors in the root directory. Any subdirectories named vendors will be ignored as well.

If they existed, these directories would also be ignored:

/applications/vendors
/vendors
/app/vendors/

Although you don’t need to, I’d recommend appending a forward slash to the end of every directory in your .gitignore file. There are two reasons for doing this:

  • It will help others understand that you are ignoring a directory.

  • If you had a file called vendors a directory called vendors, using a slash will ensure that only the directory is ignored.

Just like with files, you can tell Git to ignore just the vendors directory in the root of your project by adding a forward slash to the beginning of the pattern:

/vendors/

Making exceptions

Perhaps you’ve decided that you want to ignore every PHP file in your project, however you’d like to keep config.php in the root of your working directory.

All you need to do is add ! to the beginning of the pattern:

# Ignore all PHP files
*.php

# Keep the home page
!/config.php

Using Comments in .gitignore

Any blank lines in .gitignore files are ignored by Git. Though if you would like to use comments you can start the line with # .