What is .gitignore used for?

The .gitignore file is a text file in a repository. The purpose of .gitignore is to instruct Git which files, directory or patterns needs to be ignored in the repository.

Sometimes, we have some files or directory in our project directory which we do not want to be tracked.

For example- /node_modules, packages, .DS_Store, or project-specific data like .log, .env, temp files or any file which you think need not be tracked and committed. It's when the .gitignore file comes into play.

Watch video tutorial ðŸ‘‡

Here is a .gitignore file in one of my Laravel based project -

/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor
/.idea
/.vscode
/.vagrant
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
.env
.phpunit.result.cache
# personal rules
/site-content
/temp-files
*.log

How does .gitignore work?

If you have cloned any repository, chances are .gitignore file is already there sitting in the root of the repository.

Generally, the .gitignore is lives in the root of the repository. Though, we can have a separate .gitignore for each sub-directories of our repository as well to ignore tracking of files of that sub-directory.

In case you have just initialized the repository, you need to manually create a .gitignore file.

How do I create a .gitignore file?

The .gitignore file lives in the root of our project/repository.

Let's create one.

Open the terminal in your repository and execute -

touch .gitignore

This will create an empty, nameless text document inside the repository.

That is all. Now let's add some rules and tell Git to ignore files as per the rules we are going to specify in it.

.gitignore file syntax -

  1. * (Asterisk) is used as a wildcard match i.e - *.log
  2. / (Forward slash) is used to ignore pathnames relative to the .gitignore file i.e - /temp-files
  3. # (Number sign or Hash) is used to add comments to a .gitignore file i.e - # My custom rules

So here is the basic rule for my Node based project -

/node_modules
/.idea
/.vscode
npm-debug.log

# personal rules
/site-content
/temp-files
*.log

Note: On the basis of language, system and different type of frameworks, GitHub has a list of recommended .gitignore file - A collection of .gitignore templates you may use.

Moving forward, all the above rules we created, will affect untracked files only. If we need to ignore file or directory which we have already committed, we need to un-track them first -

git rm --cached filename

Commit .gitignore file

It is useful to commit the .gitignore file simply because we do not want our team members or collaborators to create these rules again in their repository when they clone or fork the repository.