Sub topic 6
Keeping .env out of Git
This chapter assumes you know basic Git (init, add, commit, push), can read a short shell session, and already have a .env file holding LLM_API_KEY from the previous chapter. The goal is to make sure that file can never end up in a commit, and to know what to do if it already has.
Why .env is a Git problem
Git tracks every file you add with git add. It does not know that .env holds a secret. If you run git add . in a project that contains .env, the key goes into the next commit.
A commit is permanent in practice. Once the commit is pushed, the key lives in the remote repository, in every clone, and in every fork. Deleting the file in a later commit removes it from the latest snapshot only. The old commit still contains it.
A .gitignore file tells Git which paths to leave alone. It is the first line of defense, and it is cheap. It is not the only one, and this chapter covers its limits.
Adding .env to .gitignore
From the project root, append the pattern and then check it:
echo ".env" >> .gitignore
git check-ignore -v .envgit check-ignore -v prints the rule that matched, in the form source:line:pattern path. For example:
.gitignore:1:.env .envIf the command prints nothing and exits with status 1, Git does not ignore the file. Fix the pattern before you do anything else.
Run the check every time you set up a new project. It takes a second and it tests the real behavior instead of your memory of what you typed.
Pattern details that matter
A few .gitignore rules cause most of the mistakes.
- A pattern without a slash, such as
.env, matches that name at any depth. A.envfile inbackend/is ignored too. - A pattern with a leading slash, such as
/.env, matches only at the root of the repository. .env.*matches.env.local,.env.production, and similar variants. It also matches.env.example, which you may want to commit. Handle that with a negation line (see below).- A line starting with
#is a comment. A line starting with!negates an earlier match. - Order matters. A later rule overrides an earlier one.
- Trailing spaces and wrong line endings can break a pattern. Check with
git check-ignore -v, not by eye.
A common layout ignores all .env variants but keeps a template that shows the variable names without values:
# Local secrets
.env
.env.*
# Keep the template that documents required variables
!.env.exampleThe .env.example file looks like this:
# .env.example
LLM_API_KEY=New contributors copy it to .env and fill in their own key. This gives the team a record of which variables the app needs, without sharing any values.
The tracked-file trap
.gitignore only affects files that Git does not already track. If .env was committed even once, adding it to .gitignore later does nothing. Git keeps tracking changes to it.
Check whether a file is tracked:
git ls-files .envIf this prints .env, the file is tracked. If it prints nothing, it is not.
To stop tracking it while keeping your local copy:
git rm --cached .envThe --cached flag removes the file from the index (Git's staging area) only. Without it, Git also deletes the file from disk. After running this, commit the removal, and make sure .env is in .gitignore.
Checking before you commit
Do not rely on git add . behaving. Look at what is staged before every commit, especially in a new project.
git status --short
git diff --cached --name-onlygit status --short shows a compact list. A line starting with ?? is an untracked file. A line starting with A is staged for addition. If .env appears in the staged list, unstage it:
git restore --staged .envYou can also test a path directly without staging anything:
git add --dry-run .--dry-run prints what would be added and changes nothing. If .env is in that output, your ignore rule is not working.
Ignoring files globally
Some files belong in every project you ever create. Git supports a per-user ignore file that applies to all repositories on your machine.
git config --global core.excludesFile ~/.gitignore_global
echo ".env" >> ~/.gitignore_globalThis protects you in repositories where you forgot to add the rule. It has one drawback: it lives on your machine only. A teammate who clones the project does not get your global rules, so the project's own .gitignore must still list .env. Treat the global file as a backup, not a replacement.
There is also .git/info/exclude, a per-repository ignore file that is never committed. It suits personal files that other contributors do not need to know about.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `.env` shows as untracked (`??`) after you added the rule | The rule has a typo, a trailing space, or is in the wrong directory | Run `git check-ignore -v .env` and fix the file that `.gitignore` lives in |
| `.env` shows as modified (`M`) | The file is already tracked | `git rm --cached .env`, commit, then confirm with `git check-ignore -v .env` |
| `.env.example` is ignored too | `.env.*` matches it | Add `!.env.example` after the broader rule |
| A `.env` in a subfolder is committed | Rule is `/.env`, which only matches the root | Use `.env` without the slash, or add the subfolder path |
| Ignore works for you but not a teammate | Rule is only in your global ignore file | Put it in the project's `.gitignore` |
| Key found in an old commit | The file was committed before the rule existed | Revoke the key first, then clean history if needed |
Order of operations for a new project
Do these steps in order. The order is the safety feature.
- Run
git init(or clone the repository). - Add
.envto.gitignore. - Verify with
git check-ignore -v .env. - Commit
.gitignore. - Only now create the
.envfile and paste the key.
If you create .env first and ignore it later, there is a window where a careless git add . captures it. Reversing the order removes that window.
What .gitignore cannot do
.gitignore prevents accidents with Git. It does not protect the key from other paths:
- It does not stop you from pasting the key into a source file, which Git will happily commit.
- It does not stop
git add -f .env, which forces an ignored file into the index. - It does not stop tools that copy your whole folder, such as a Docker build that runs
COPY . .or a zip archive you email. - It does not scan content. A key hard-coded in
app.pyis committed even if.envis perfectly ignored.
Catching those cases takes scanning tools and pre-commit checks, which a later chapter covers. For now, use .gitignore as the base layer and confirm it works with a test, not with trust.
Exercise
You added .env to .gitignore, but git status still shows M .env. What is happening, which command fixes it, and why is the fix not enough if the file was ever pushed?
Show answer
The file is already tracked, and .gitignore does not affect tracked files. Run git rm --cached .env, commit the removal, and confirm with git check-ignore -v .env. This is not enough after a push because earlier commits still contain the key in history, in the remote, and in clones. The key must be revoked and replaced.
Exercise
Your .gitignore contains .env.* and you want teammates to get a template file showing which variables are needed. Which file name and which extra line do you use, and what should the file contain?
Show answer
Name it .env.example and add !.env.example after the .env.* line so the broader rule does not ignore it. The file should list variable names with empty values, such as LLM_API_KEY=, and never a real key.