Ignoring unwanted files
How to tell Git which files shouldn’t be tracked.
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. 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 package managers (e.g.
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
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.
Let's say you have the following directory tree:
. ├── README ├── config.yml ├── foo │ ├── config.yml │ └── foo.php └── index.php
If you wanted to ignore all the
config.yml files, you just need to enter:
With this pattern, both of these files would be ignored:
To just ignore the
config.yml in the root directory, you can prefix the pattern with a forward slash, just like this:
Want to ignore all of the PHP files in your project? This pattern will do that for you:
The process for ignoring folders is very similar. Just enter the name of the folder:
With this pattern, Git won't just ignore
foo in the root directory. Any subdirectories named
foo will be ignored as well.
If they existed, these directories would also be ignored:
Although you don't need to, I'd recommend appending a forward slash to the end of every directory in your
There are two reasons for doing this:
- It makes it clearer to others that you're ignoring a directory.
- If you had a file called
fooand a directory called
foo, using a slash will ensure that only the directory is ignored.
Just like with files, you can tell Git to ignore just the
foo directory in the root of your project by adding a forward slash to the beginning of the pattern:
Perhaps you've decided that you want to ignore every PHP file in your project, however you'd like to keep
index.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 !/index.php
It’s also worth mentioning that blank lines are ignored by Git so they can be used for spacing and lines that start with
# are comments.
Want to learn more about Git?
This tutorial is part of a free beginner-friendly course!