1. Home
  2. Blog
  3. DevOps

DevOps

Gitignore Explained: Patterns, Negation, check-ignore and Tracked File Fixes

A gitignore file tells Git which untracked files to leave alone, such as build output, logs and secrets. Learn how the patterns really match, why a negation sometimes does nothing, how to debug any rule with git check-ignore, and how to stop tracking a file you already committed.

9 min read
Gitignore explained with patterns, negation, check-ignore and tracked file fixes

Key takeaways

  • A gitignore file only affects untracked files. A file you already committed stays tracked until you run git rm --cached.
  • A leading slash anchors a pattern to the folder of the .gitignore; a trailing slash matches folders only.
  • Git never looks inside an ignored folder, so logs/ plus !logs/.gitkeep does not work, while logs/* plus !logs/.gitkeep does.
  • git check-ignore -v file names the exact file, line and pattern that ignores a path.

Every repository collects files that should never be committed: compiled output, dependency folders, editor settings, log files, and the one everybody fears, a .env file full of secrets. A gitignore file is how you tell Git to stop showing them in git status and stop adding them with git add .. The basic idea is simple, but the matching rules have a few traps that confuse even experienced developers.

We built a small repository and tested every rule in this guide with Git 2.56 on Windows. Git used a throwaway identity, so the outputs contain nothing personal. New to Git? Start with our Git tutorial for beginners.

What a gitignore file does

A file named .gitignore holds one pattern per line. Git checks each untracked path against those patterns. If a path matches, Git treats it as ignored: git status hides it and git add . skips it. Lines starting with # are comments and blank lines are ignored.

You usually keep one .gitignore at the root of the repository and commit it, so the whole team shares the same rules. You can also put extra .gitignore files in subfolders; their patterns are relative to that folder.

Our test repository

We created these files in a fresh repository:

app.log  important.log  notes.txt  .env  .env.example
logs/.gitkeep  logs/today.log
build/app.exe  docs/build/index.html
src/main.py  src/__pycache__/main.cpython-313.pyc

Then we added this .gitignore:

# logs, but keep one
*.log
!important.log
# keep the folder via .gitkeep: ignore contents, not the folder
logs/*
!logs/.gitkeep
# build output only at the root
/build/
__pycache__/
# secrets, but share the template
.env
!.env.example

Here is what git status --short --untracked-files=all showed afterwards:

?? .env.example
?? .gitignore
?? docs/build/index.html
?? important.log
?? logs/.gitkeep
?? notes.txt
?? src/main.py

Seven files remain visible. The secrets file, the logs, the compiled build and the Python cache are hidden. The sections below explain each line.

Pattern rules

Pattern Matches
*.log Any file ending in .log, in any folder
.env A file or folder named .env, in any folder
__pycache__/ Folders named __pycache__ anywhere, and everything in them
/build/ Only the build folder at the root
logs/* Everything directly inside the root logs folder
docs/**/*.pdf PDF files at any depth under docs
temp?.txt temp1.txt, tempA.txt, but not temp10.txt
!important.log Re-includes a file that an earlier pattern ignored

A * matches anything except a slash, ? matches one character, and ** matches across any number of folders. Character ranges like [0-9] also work.

Leading and trailing slashes change everything

Two small characters decide where a pattern applies:

  • No slash (build): matches a file or folder with that name at any depth.
  • Trailing slash (build/): matches folders only, at any depth.
  • Leading slash (/build/): matches only next to the .gitignore file.
  • Slash in the middle (docs/build): also anchored, relative to the .gitignore.

Our test proves it. /build/ hid build/app.exe at the root, but docs/build/index.html still appeared in git status. That was intentional here, because generated docs might be committed on purpose. If you want every build folder ignored, drop the leading slash.

Negation with !

A line starting with ! re-includes paths that an earlier line excluded. Order matters, because Git reads the file top to bottom and the last matching pattern wins. In our example, *.log ignores every log, then !important.log brings one back:

.gitignore:2:*.log	app.log
.gitignore:3:!important.log	important.log

If you swapped those two lines, *.log would come last and win, and important.log would be ignored again. The same pattern keeps a .env.example template in the repository while the real .env stays out, which is exactly what our environment variables guide recommends.

The parent folder trap

This is the rule that catches most people. Git does not look inside a folder that is ignored, so a negation for a file inside it can never match. We tested it with a folder called trap:

# does NOT work
trap/
!trap/keep/a.txt

git status showed nothing at all under trap/; the negation was silently ignored. The fix is to ignore the folder’s contents instead of the folder, then re-include the subfolder:

# works
trap/*
!trap/keep/
?? trap/keep/a.txt

Now Git enters trap, ignores trap/b.txt, and keeps trap/keep/a.txt. The same reasoning explains our logs/* plus !logs/.gitkeep lines, the standard way to commit an otherwise empty folder.

Tip: when a negation “does nothing”, the cause is almost always an ignored parent folder. Change folder/ to folder/* and re-include each level you need.

Debug any rule with git check-ignore

Instead of guessing, ask Git which rule applies. The -v flag prints the file, line number and pattern:

git check-ignore -v app.log important.log logs/today.log logs/.gitkeep build/app.exe .env src/__pycache__/main.cpython-313.pyc
.gitignore:2:*.log	app.log
.gitignore:3:!important.log	important.log
.gitignore:5:logs/*	logs/today.log
.gitignore:6:!logs/.gitkeep	logs/.gitkeep
.gitignore:8:/build/	build/app.exe
.gitignore:11:.env	.env
.gitignore:9:__pycache__/	src/__pycache__/main.cpython-313.pyc

Lines that start with ! mean the path is matched by a negation, so it is not ignored. Add -n to also list paths that match nothing; they show as :: followed by the path, as notes.txt did in our run.

One catch we hit: by default, check-ignore says nothing about files that are already tracked. After committing notes.txt and adding it to .gitignore, a plain git check-ignore -v notes.txt printed nothing and exited with code 1. Adding --no-index showed the matching rule. Tracked files are the subject of the next section.

Ignoring a file you already committed

A gitignore rule has no effect on tracked files. We committed config.local, then added it to .gitignore and edited it. Git still reported the change:

 M .gitignore
 M config.local

To stop tracking it while keeping your local copy, remove it from the index only:

git rm --cached config.local
git commit -m "stop tracking config.local"

After the commit, git status was clean and config.local still existed on disk. For a whole folder, use git rm -r --cached folder/.

Two warnings. First, this removes the file from the repository for everyone: teammates who pull the commit will have the file deleted from their working copy, so tell the team and provide a template. Second, if the file held secrets, they are still in the history. Rotate those secrets immediately, and treat any key that was ever pushed as leaked. Our SSH keys guide covers generating replacements.

Local and global ignores

Not every rule belongs in the shared file:

  • .git/info/exclude: same syntax, but never committed. Use it for personal scratch files in one repository. We added scratch.txt there and check-ignore reported .git/info/exclude:7:scratch.txt.
  • Global excludes file: set with git config --global core.excludesFile ~/.gitignore_global, for things that apply to all your repositories, such as .DS_Store, Thumbs.db or your editor’s folder.

Keep OS and editor files in your global file rather than every project’s .gitignore; the project file should list what the project generates.

Cleaning up ignored files

git clean deletes untracked files. Always run it with -n (dry run) first. The -X flag limits it to ignored files only:

git clean -ndX
Would remove .env
Would remove app.log
Would remove build/
Would remove config.local
Would remove logs/today.log
Would remove scratch.txt
Would remove src/__pycache__/
Would remove trap/b.txt

Notice .env in the list. Running the real command with -f would delete your local secrets file, so read the dry run carefully. To set work aside rather than delete it, see our git stash guide.

A starter template

A sensible base for a Python and Node project:

# dependencies
node_modules/
.venv/

# build and cache output
dist/
build/
__pycache__/
*.pyc
.pytest_cache/
coverage/

# logs and local data
*.log
*.sqlite3

# secrets, keep the template
.env
.env.*
!.env.example

GitHub publishes ready-made templates per language in its github/gitignore repository, and new repositories on GitHub can start from one. Trim them to what your project actually produces.

Common mistakes

  • Expecting it to untrack files: it only affects untracked paths. Use git rm --cached.
  • Negating inside an ignored folder: ignore folder/*, not folder/.
  • Wrong order: a negation must come after the pattern it overrides.
  • Trailing spaces: spaces at the end of a line are ignored unless escaped with a backslash, which can make a pattern differ from what you see.
  • Ignoring lock files: package-lock.json and similar lock files should usually be committed for repeatable builds.
  • Relying on it for security: it is a convenience, not protection. Add secret scanning in a pre-commit hook as well.

Final thoughts

A good gitignore keeps your repository clean and your secrets out of history. Remember the four rules our tests confirmed: slashes decide where a pattern applies, the last matching line wins, Git never looks inside an ignored folder, and tracked files need git rm --cached. When a rule does not behave, git check-ignore -v tells you exactly why in one command.

Frequently asked questions

Why is my gitignore not working?

Usually because the file is already tracked. Gitignore only affects untracked files, so remove the file from the index with git rm and the cached option, then commit. Also check that a negation is not inside an ignored folder.

How do I ignore a folder but keep one file inside it?

Ignore the folder contents with folder/* instead of folder/, then add a negation such as !folder/.gitkeep on a later line. Git cannot re-include files inside a folder that is ignored as a whole.

How do I see which rule ignores a file?

Run git check-ignore -v followed by the path. It prints the gitignore file, the line number and the pattern that matched. Add the no-index option for files that are already tracked.

Should the gitignore file be committed?

Yes. Commit the project gitignore so the whole team shares the same rules. Keep personal patterns in .git/info/exclude or a global excludes file instead.

Does gitignore remove secrets from Git history?

No. It only stops new untracked files from being added. If a secret was committed, it stays in history, so rotate it immediately and consider rewriting history with a dedicated tool.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Software Development

Python Map and Filter: Examples vs List Comprehensions

Python map and filter explained with tested examples: lazy map objects, multiple iterables, filter(None), chaining, and a timed comparison with…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →