.gitignore File: What It Is and How It Works in Git
.gitignore file tells Git which files or folders to ignore and not track in a project. It helps keep temporary, sensitive, or unnecessary files out of your Git history.How It Works
Think of the .gitignore file as a filter or a list of rules that tells Git which files it should pretend don't exist. When you add or commit changes, Git looks at this file and skips any files or folders that match the patterns inside it.
This is useful because many projects create files that don't need to be saved in Git, like temporary files, logs, or personal settings. By ignoring these, your project stays clean and only contains the important files.
It's like packing for a trip and making a checklist of things you don't want to bring along. Git uses the .gitignore file to know what to leave behind.
Example
This example shows a simple .gitignore file that ignores log files, temporary files, and a folder named temp.
node_modules/
*.log
temp/
.DS_StoreWhen to Use
Use a .gitignore file whenever you want to keep certain files out of your Git repository. Common cases include:
- Ignoring build or dependency folders like
node_modulesordist. - Skipping personal editor or IDE settings files.
- Excluding sensitive files like passwords or API keys.
- Preventing temporary or log files from cluttering your project history.
This keeps your repository clean, reduces size, and protects sensitive information.
Key Points
- The
.gitignorefile controls which files Git ignores. - It uses simple patterns to match files and folders.
- Helps keep your repository clean and secure.
- You can have multiple
.gitignorefiles in different folders. - Changes to
.gitignoreonly affect untracked files, not files already tracked by Git.