How to prevent committing a .env file

.gitignore alone isn't enough: it doesn't apply to files already tracked, git add -f bypasses it, and a new repo often doesn't have one yet. Use three layers.

1. .gitignore (baseline)

.env
.env.*
!.env.example

2. A pre-commit hook that checks what's staged

A minimal hand-rolled version:

#!/bin/sh
# .git/hooks/pre-commit
if git diff --cached --name-only | grep -E '(^|/)\.env($|\.)' | grep -v '\.example$'; then
  echo "refusing to commit .env files"; exit 1
fi

Or install KatchPath, which also checks key-shaped strings, private keys, build folders and blanket git add -A from the wrong directory:

curl -fsSL https://katchpath.com/install.sh | sh
katchpath install --global   # every repo on this machine

3. A CI check

Hooks live on laptops and can be skipped with --no-verify. A CI step on every pull request is the backstop. The KatchPath Team Pack ships a ready GitHub Action for that.