.gitignore — Files That Should Never Be Tracked
Asha's editor drops a .DS_Store file into every folder, and she has a secrets.txt holding an API key for a recipe-search tool. Neither belongs in history. Every git status lists them as untracked, and one careless git add . would commit them. A .gitignore file stops that.
The rule
.gitignorehides untracked files from Git; it cannot un-track a tracked one.
Create a plain text file called .gitignore in the repository's top folder, one pattern per line:
# system clutter
.DS_Store
# private settings
secrets.txt
.env
# anything that ends in .log
*.log
# a whole folder
cache/
# everything inside build/ ...
build/*
# ...except this one file
!build/README.mdHow patterns read:
secrets.txtmatches a file with that name in any folder.*.logmatches any name ending in.log;*stands for any run of characters.- A trailing
/, as incache/, matches only folders. - A leading
/, as in/notes.txt, matches only at the top of the repository. !re-includes something an earlier line excluded. It cannot rescue a file whose parent folder is itself ignored, which is why the example ignoresbuild/*, the folder's contents, rather thanbuild/itself.#starts a comment.
Commit the .gitignore itself, so everyone who clones the repository shares the same rules.
The key limit: Git only ignores files it is not already tracking. If secrets.txt was committed before the rule was added, Git keeps tracking it. Stop tracking it without deleting your local copy:
git rm --cached secrets.txt
git commit -m "Stop tracking secrets file"That removes it from future snapshots, but it is still visible in older commits. If a real secret was ever committed, treat it as leaked and replace it.
The shortcut
For each file, ask "Is it generated, personal or secret?" Generated by a tool (build output, logs, caches), personal to your machine (editor and OS files) or secret (keys, passwords): ignore it. Otherwise, commit it.
List the untracked files
git statusshows.DS_Store,secrets.txt,app.logandsoup.md.
To find out which rule is hiding a file, run git check-ignore -v app.log; it prints the file and line of the matching pattern.
Drills
Answer fast — trust the rule.
Which pattern ignores every file ending in .log?
secrets.txt was committed last week. Asha now adds secrets.txt to .gitignore. What happens?
Which of these should normally be committed rather than ignored?
What does git rm --cached secrets.txt do?
Remember
.gitignorehides untracked files from Git; it cannot un-track a tracked one.- Generated, personal or secret: ignore it. Everything else: commit it.
- Already committed?
git rm --cached, and treat any leaked secret as compromised.
