Advanced GitIgnore Usage – Ignore and Exclude Specific Files

In the previous blog, we learned how the .gitignore file helps you prevent unwanted files (like logs, build artifacts, or secrets) from being tracked in Git.

In this blog, let’s go deeper and explore advanced .gitignore rules with practical scenarios.


Problem 1 – Ignore All .properties Except One

Imagine you have multiple configuration files:


development.properties
production.properties
example.properties

You want Git to ignore everything except example.properties.

.gitignore

*.properties
!example.properties
  • *.properties → ignore all .properties files
  • !example.properties → exception → don’t ignore this file

✅ Only example.properties will be staged. New developers can use example.properties as a template to add their own credentials.


Problem 2 – Ignore Root File But Not Same in Subfolder

Suppose your project has:

docs.md
/docs/readme.md
/docs/example.md

You want to ignore only the docs.md at root, but still keep files inside /docs/.

.gitignore

/docs.md

✔️ Only the root docs.md is ignored. ✔️ Files inside /docs/ remain visible to Git.

Important Rule:

  • Writing just docs.md will ignore all files named docs.md in the project (root + subfolders).
  • Writing /docs.md ignores only the root-level file.

Problem 3 – Explicit Path vs Recursive Pattern

  • docs.md → ignores all docs.md files everywhere.
  • /docs.md → ignores only the root one.
  • docs/*.md → ignores all .md files inside the docs/ folder.

Practical Use Cases

  • Node.js projects:
node_modules/
  • Java projects:
*.class
target/
  • Go projects:
*.exe
*.out
  • Python projects:
__pycache__/
*.pyc

Key Takeaways

  • Use ! for exceptions (don’t ignore specific files).
  • Use /filename to ignore only root-level files.
  • Use folder patterns (docs/*.md) to ignore files only inside specific directories.
  • Combine multiple rules to keep your repo clean and secrets safe.

Coming Up Next

In the next blog, we’ll tackle multi-service repositories – where different microservices (Go, Python, Java, Node.js) live inside one repo, and how to manage .gitignore rules for each service cleanly.


Keep Learning 🚀

🚀 Don’t Miss Out!

Now you know how to use .gitignore to filter out unnecessary files. In the next blog, we’ll dive deeper into exceptions and path-specific ignores.

👉 Subscribe to Learning Ocean – Subscribers get coupon codes, early access to blogs/courses, and exclusive YouTube content.

👉 My YouTube Channel

👉 Watch this video explanation

Stay curious, keep coding, and let’s master Git together! 🎉