Sub topic 6
Keeping .env out of Git
This chapter assumes you can run basic Git commands and that you already have a local .env file holding LLM_API_KEY, as set up in the previous chapter. It covers how to stop Git from tracking that file, how to confirm it, and what to do if the file was committed anyway.
Why .gitignore matters here
A .env file is plain text in your project folder. Git does not know it is secret. If you run git add . or git commit -a, Git will stage the file like any other. Once the commit is pushed, anyone with read access to the repository can see the key. On a public repository, automated scanners find exposed keys within minutes.
A .gitignore file lists path patterns that Git should skip. Ignored files do not show up in git status and are not staged by git add ..
Ignore the file
Add .env to .gitignore and ask Git to confirm that the rule matches.
echo ".env" >> .gitignore
git check-ignore -v .envgit check-ignore -v prints the rule and the line that matched, for example .gitignore:1:.env .env. If it prints nothing, the file is not ignored and you need to fix the pattern before you commit.
Commit the .gitignore file itself so that everyone who clones the repository gets the same rule.
How the decision flows
Git checks whether a file is already tracked before it applies ignore rules. That detail causes the most common mistake, described below.
Common error: .env was already committed
Adding a file to .gitignore does not stop Git from tracking a file it already tracks. If .env was committed earlier, git status will keep showing changes to it. You can stop tracking it and keep your local copy with this command.
git rm --cached .envThen commit the removal. The --cached flag removes the file from the Git index only, so the file stays on disk.
Other patterns to know
Projects often use several env files, such as .env.local or .env.production. A single .env rule does not match those names. A wildcard rule with an exception for the example file covers them.
.env
.env.*
!.env.exampleOther things to keep in mind:
- A rule in a nested directory's
.gitignoreapplies only to that directory and below. - A global ignore file (set with
git config --global core.excludesFile) protects every repository on your machine, but it does not protect teammates. - Ignoring only prevents accidents with Git. It does not stop the key from appearing in logs, screenshots, or backups.
Exercise
You added .env to .gitignore, but git status still lists .env as modified. What is the likely cause, and what do you do?
Show answer
The file was committed before the rule existed, so Git still tracks it and ignore rules do not apply to tracked files. Run git rm --cached .env and commit the removal. Because the key is in history, revoke it and create a new one.