How to use .gitignore in your repositories?

What is .gitignore?

  • It basically contains the list of files or directories that should be ignored and not tracked by Git while pushing on a repository.

  • Although there can be multiple .gitignore files in a single repository, It is a best practice to have a single file in the root directory of your repository.

  • Let's look at how you can ignore files and folders,

Assuming your directory tree looks something like this,

repository
├── .gitignore
├── frontend
│   # files and folders in frontend
│   
└── backend
    ├── env
    │   # files and folders in env
    │
    └── test.log

Ignore files

# for a single file

backend/test.log

# for files having .log extension in the entire repository

*.log

# for files having .log in backend directory

backend/*.log

Ignore directories

# for a directory including all the subdirectory inside it

backend/env/

Why use .gitignore?

  • It helps in preventing unintended files from being committed to the repository.

  • There may be device-specific environments or sensitive information like deployment keys that need to be ignored to maintain privacy.

Best practices you should follow

  • Create a .gitignore file in the root directory of your repository as soon as you initialize it.

  • If there are multiple sections in your repository, add comments to separate them and increase readability.

  • Check .gitignore before pushing on your repository to check if any necessary files like requirements.txt are ignored.

  • Although you can use wildcards to target multiple files, It is recommended to be specific if possible.