Protect .env files
Two layers that keep the secrets in .env away from Claude. Deny rules in permissions stop the file tools from reading or editing the usual secret files (.env, .env.local, .env.production…); the hook also blocks Bash commands that mention them, such as cat or source. .env.example stays readable.
Tested with Claude Code 2.1.329
.claude/hooks/protect-env.sh
#!/bin/bash
# Blocks Bash commands that touch a .env file (but not .env.example). Exit 2 = block.
cmd=$(jq -r '.tool_input.command // empty')
[ -z "$cmd" ] && exit 0
cleaned=$(echo "$cmd" | sed -E 's/\.env\.(example|sample|template)//g')
if echo "$cleaned" | grep -Eq '(^|[[:space:]/"'\''=<>])\.env([.][A-Za-z0-9_-]+)?([[:space:]"'\'';|&>]|$)'; then
echo "Blocked: this command touches a .env file, which holds secrets. Use .env.example to see which variables exist." >&2
exit 2
fi
exit 0
.claude/settings.json
{
"permissions": {
"deny": [
"Read(./.env)",
"Read(./**/.env)",
"Read(./.env.local)",
"Read(./.env.*.local)",
"Read(./.env.production)",
"Read(./.env.development)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-env.sh"
}
]
}
]
}
}
Notes
- Needs jq. Run `chmod +x .claude/hooks/protect-env.sh` once.
- Neither layer is absolute; a script that reads .env internally still can. Keep real production secrets off developer machines.
- If `.claude/settings.json` already has `permissions` or `hooks`, merge these in instead of replacing it.
- Deny always wins over allow, so `Read(./.env.*)` is avoided: it would block .env.example too. Add your other secret file names to the deny list.