How to prevent committing .env files to git
1. Set Up a System-Wide Global .gitignore
Instead of relying on remembering to create a .gitignore in every new scratch project, configure a system-wide gitignore rule once:
# Create global ignore file:
touch ~/.gitignore_global
git config --global core.excludesfile ~/.gitignore_global
# Append env file patterns:
echo ".env" >> ~/.gitignore_global
echo ".env.*" >> ~/.gitignore_global
echo "*.env" >> ~/.gitignore_global
echo "!.env.example" >> ~/.gitignore_global
Notice the !.env.example exception: this ensures template files without real secrets can still be tracked.
2. What to Do If the .env File is Already Tracked
Adding a file to .gitignore does NOT untrack it if git already indexed it. You must remove it from the index without deleting the local file:
git rm --cached .env
git commit -m "Untrack .env file"
3. Add a Lightweight Pre-Commit Hook
Create an executable script at .git/hooks/pre-commit:
#!/bin/sh
if git diff --cached --name-only | grep -E '(\.env|\.env\..*)$'; then
echo "\033[0;31m[Error]\033[0m Refusing to commit .env file!"
exit 1
fi
Make it executable with chmod +x .git/hooks/pre-commit.