Why duplicate keys in .env are dangerous
A duplicated key does not throw an error. The loader silently picks one value, and which one depends on the tool:
| Loader | Duplicate key in the same file | Already set in the environment |
|---|---|---|
| dotenv (Node.js) | last value wins | environment wins (unless override: true) |
node --env-file | last value wins | environment wins |
| python-dotenv | last value wins | environment wins (unless override=True) |
Docker Compose env_file | last value wins | environment: in compose.yaml wins |
The typical bug: someone adds DATABASE_URL at the bottom of a long file to "try something", forgets it, and staging talks to the wrong database for a week. The cleaner keeps the effective value and removes the dead line, so what you read is what the app gets.
What the cleaner changes and what it leaves alone
| Input | Default result | Option |
|---|---|---|
second API_KEY= further down | first one removed | dedupe |
SENTRY_DSN= | removed | remove empty values |
# comment line | kept | removed with strip comments |
PASS="a#b" # note | kept as is | becomes PASS="a#b" with strip comments |
export TOKEN='x' | kept as is | never changed |
| trailing spaces, 3 blank lines | trimmed, one blank line | always |
To sort keys or align the = signs, run the result through the .env formatter. To combine several files first, use the ENV merger and then clean the merged output.
Finding duplicates on the command line
# list keys defined more than once grep -oE '^(export )?[A-Za-z_][A-Za-z0-9_]*=' .env \ | sed -E 's/^export //; s/=$//' | sort | uniq -d
Add it to a pre-commit hook or a CI step that runs on .env.example to stop duplicates from coming back.