A .gitignore file tells Git which intentionally untracked files should normally be left outside the repository. It can hide local caches, compiler output, downloaded dependencies, editor files and machine-specific settings from ordinary status and staging operations. It does not erase files, remove existing commits or protect credentials already disclosed in a remote repository.
The last limitation is important. Git records snapshots through its index and commit history. Ignore patterns mainly affect new, untracked paths; they do not change the tracking of paths already committed. A good setup identifies which files teammates actually need, applies narrow rules and checks their effect before anyone relies on them.
Start with the purpose of a .gitignore
Projects generate many files that are useful during development but unnecessary to share. A compiler may create object files; a testing framework may create coverage reports; an editor may create local state. Listing these files in .gitignore keeps routine output focused on meaningful source changes. It can also reduce the chance of accidentally staging an environment file, although it cannot substitute for secrets management.
The official gitignore documentation defines the matching rules and explains which exclusion sources Git consults. The key point is that a path must be untracked for the ignore rules to have their normal effect. Once Git is tracking a path, adding a pattern for it does not make that path disappear from the index.
Check git status before editing a repository. If an unexpected file already appears in the staged or tracked set, establish how it arrived there. Do not respond automatically with a broad command that removes many files. An ignore rule is most helpful when it expresses a deliberate project policy that contributors can understand.
Create and commit a shared ignore file
Place a plain text file named exactly .gitignore at the root of the repository for general project exclusions. Additional .gitignore files can exist in subdirectories if those subprojects need more specific rules. Add concise comments to document unusual choices, then commit the ignore file itself so all collaborators receive the same conventions.
A simple JavaScript-based web project might begin with these entries:
# Dependencies installed locally
node_modules/
# Generated output
dist/
coverage/
# Personal environment settings
.env
.env.local
.env.*.local
# Editor and operating-system files
.DS_Store
*.swp
These are examples, not a rule that every application must exclude the same paths. Some repositories intentionally track generated code or certain manifests to make builds reproducible. Keep required lockfiles or configuration files when the project’s workflow depends on them. Test a clean clone to confirm a teammate can build the application from tracked inputs and documented dependencies.
Do not add real secrets to an example configuration. If collaborators need to know which environment variables are required, create a separate placeholder file that contains invented values, document it and review what it reveals. Make sure the intended local configuration files are actually excluded under the project’s patterns.
Understand wildcards and matching by directory
An ignore pattern such as *.log matches matching files beneath the relevant .gitignore scope. A trailing slash identifies a directory: build/ ignores directories called build and their contents, not an ordinary file named build. A leading slash anchors a pattern to the directory where that .gitignore lives; at repository root, /build/ only applies to the root build directory.
Patterns containing a slash in the middle also refer to a relative path. For example, docs/generated/ points to that path relative to the containing ignore file rather than any folder named generated in the repository. An ignore file under frontend/ applies to paths within that subdirectory, not a sibling project outside it.
Git supports ? for a single non-separator character and bracket groups such as [0-9]. Special uses of ** can match across directory levels; for example, reports/**/draft.txt can match draft.txt directly inside reports or under deeper folders. These are Git-style glob rules, not arbitrary regular expressions. When the intention is unclear, check the official pattern-format rules instead of guessing.
Be cautious with very broad patterns. Excluding every *.json file would hide potentially important configuration or test fixtures from normal staging. A narrow pattern for actual generated output is usually easier to maintain and less likely to surprise someone who clones the repository.
Use negation without accidentally hiding the parent
A leading ! can negate an earlier ignore pattern, subject to the rules for pattern precedence and directory traversal. For example, an application could ignore local environment files but keep one safe example:
.env*
!.env.example
Here the project could track an .env.example containing placeholder field names while leaving local .env data untracked. This works when the relevant parent directory remains visible to Git. It is not a guarantee that the example file is safe; developers must still inspect its content before committing.
Git cannot re-include a file inside a parent directory that is itself excluded if the parent is not traversable under the applicable patterns. For example, ignoring generated/ and then writing !generated/README.md alone is not sufficient to bring back the nested file. You may need a more precise exclusion that keeps the relevant parent path visible. Excessive negation rules often signal that the ignore policy should be simplified.
The same source defines pattern precedence: within one level, the last matching applicable pattern can change the outcome, while nested .gitignore rules can override applicable higher-level rules. Test the exact file path rather than treating the pattern list as a generic top-to-bottom instruction script.
Distinguish shared, local and global exclusions
Rules intended for everyone should generally live in a committed .gitignore. A rule specific to one local clone can be placed in .git/info/exclude without changing the shared repository. User-wide preferences can be configured using core.excludesFile, pointing to an appropriate excludes file in the user’s configuration. These sources have different precedence levels and scopes.
The official Pro Git book explains why automatically generated artifacts are common ignore candidates. It also describes personal exclude preferences. Do not put a team-required exception in a personal global file that only works on one machine; other contributors and automated builds will not necessarily have the same configuration.
A nested monorepository may have a shared root ignore file plus a dedicated rule set within a package. Document which team owns each level. A generic root pattern that hides every directory named build may accidentally hide meaningful source code belonging to a build-tool subproject. Review the actual tree rather than borrowing the broadest possible template.
Diagnose unexpected behavior with git check-ignore
Use git check-ignore -v path/to/file.log to inspect which ignore pattern matched a candidate untracked path. The verbose output identifies the source and rule so developers can correct an unexpected exclusion. The git check-ignore reference documents the command’s options and diagnostic behavior.
Already tracked files are not normally treated as ignored by this command, because the ignore mechanism does not govern their tracked state. The --no-index option is useful when investigating what rules would match independent of the index. Separately run git ls-files -- path/to/file.log to check whether Git has a path in its index. Use both pieces of evidence instead of assuming that a pattern was never loaded.
After modifying the ignore file, test representative paths that should be ignored and others that should remain visible. Inspect git status and the staged diff. The absence of clutter is useful only when important source and build inputs are still accounted for.
Stop tracking a previously committed local file carefully
Suppose .env is tracked but the team decides local environment settings should not be committed. Adding the pattern to .gitignore does not change its tracked state. After reviewing the impact, git rm --cached -- .env removes that path from the index without deleting the working-tree copy. Use git status and git diff --cached to review the staged change before committing it.
git rm --cached -- .env
git status
git diff --cached
The git rm manual explains that --cached updates the index only. The next commit can remove the file from the tracked snapshot, but earlier commits still contain any information they originally recorded. This command also should not be applied indiscriminately to needed project files.
If real credentials were ever committed or shared, immediately address them through the affected service’s revocation or rotation procedure. Follow appropriate security-incident and history-remediation guidance. Rewriting Git history may affect collaborators and does not guarantee that copies held elsewhere disappear. .gitignore is not a cure for secrets already exposed.
Test the ignore rules before merging
A safe change can be reviewed with a small set of invented files. Create a temporary log and a sample environment placeholder, then use git check-ignore -v to understand which patterns affect them. Confirm the file that should remain tracked is not hidden. Review the diff to the .gitignore itself and run the project’s normal build or tests from an appropriately clean checkout.
When collaborating, describe why each new exclusion was needed: a compiler began generating a cache, a test runner introduced coverage output or a new editor produces local settings. Avoid hiding files merely because they appear in status once; some may be essential source files that have not yet been added. The point is to make intended repository contents clear.
During review, look for accidental global exclusions and for nested patterns that conflict. A collaborator who sees a clean status while missing required source should be able to diagnose the cause using the shared rules. Keep comments and exception paths accurate when a project evolves.
Where .gitignore fits in a reliable Git workflow
After the patterns are tested, stage only intended project changes, inspect git diff --staged and create a descriptive commit. A separate beginner Git command workflow helps distinguish staging, committing, fetching and pushing. None of those steps guarantees that a repository is safe to publish unless secrets, rights and project requirements have been reviewed.
A useful .gitignore is short enough to understand, precise enough to avoid hiding source and tested against representative paths. It keeps intentionally untracked files out of ordinary Git operations without rewriting history or managing authentication. Combined with reviewed commits and deliberate secret handling, it supports collaboration without creating false security assurances.