You can write "never edit .env" in CLAUDE.md and hope the model obeys. It works most of the time, but it is a request, not a guarantee. When the file is sensitive, the ideal is a rule the agent cannot ignore. In Claude Code, that rule is a PreToolUse hook: a script that runs before the tool and can block the action.

Claude Code: how to block edits to .env and protected files with a hook
Use a PreToolUse hook with exit 2 to prevent Claude Code from editing .env, package-lock.json, and .git, and to block dangerous Bash commands. Includes the limits of this protection.
Get AI articles in your inbox
Technical curation on models, agents and coding tools. No spam, unsubscribe anytime.
This tutorial shows how to protect .env, package-lock.json, and the .git/ folder from agent edits, and then how to block dangerous Bash commands. Everything comes from the official Claude Code hooks guide. If you have not configured any hooks yet, start with the 3-hook tutorial for notifications, Prettier, and context.
How the blocking works
The PreToolUse event fires before a tool call executes and can block it. Claude Code sends the call data as JSON to your script's standard input. For a Bash call, for example, fields arrive such as:
hook_event_name: the event that triggered the hook.tool_name: the tool Claude is about to use.tool_input: the call arguments. For Bash, thecommandfield holds the shell command.
The script responds with an exit code:
- Exit 0: no objection. Note: in a
PreToolUse, exiting with 0 does not approve the call; it follows the normal permission flow. - Exit 2: blocks. What you write to stderr returns to Claude as feedback, and it adjusts its approach.
With any other code and no valid JSON in the output, the action proceeds in most events.
Step 1: create the protection script
Save to .claude/hooks/protect-files.sh:
#!/bin/bash
# protect-files.sh
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
# Normaliza separadores do Windows para os padrões abaixo casarem
FILE_PATH="${FILE_PATH//\\//}"
PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")
for pattern in "${PROTECTED_PATTERNS[@]}"; do
if [[ "$FILE_PATH" == *"$pattern"* ]]; then
echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
exit 2
fi
done
exit 0The script reads the JSON, extracts the file path with jq, and compares it against the list. If it matches, it writes the reason to stderr and exits with 2. Install jq with brew install jq on macOS or apt-get install jq on Debian and Ubuntu.
Step 2: make the script executable
On macOS and Linux, Claude Code can only run the script if it is executable:
chmod +x .claude/hooks/protect-files.shStep 3: register the hook
Add to .claude/settings.json at the project root. The matcher Edit|Write makes the hook apply only to tools that modify files:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"
}
]
}
]
}
}If the file already has a hooks key, add PreToolUse alongside the existing events. The $CLAUDE_PROJECT_DIR variable points to the project root, so the path works from any subfolder.
Step 4: test
Ask Claude to add a comment to your .env. Claude Code blocks the edit before it happens and delivers the script's Blocked: message to the agent. You can also type /hooks to see the hook listed.
An important limit
The documentation itself issues a warning: the hook in Edit|Write does not cover everything. Claude can still modify protected files via shell commands. To block some of those cases, the documentation says to add a Edit deny rule by path in permissions.deny, in the .claude/settings.json, such as Edit(/.env) for the .env at the root. Even so, the .env can still be altered in other ways. To limit where commands can write, the path is to configure the sandbox.
In short: treat the hook as a layer, not a vault.
Extra: block dangerous commands in Bash
The same mechanism applies to commands. This script reads the command field and blocks a destructive database operation:
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')
if echo "$COMMAND" | grep -q "drop table"; then
echo "Blocked: dropping tables is not allowed" >&2 # o stderr vira feedback para o Claude
exit 2 # exit 2 = bloqueia a ação
fi
exit 0 # exit 0 = sem decisão; vale o fluxo normal de permissõesRegister with "matcher": "Bash" on the PreToolUse event. You can place multiple hooks on the same event. The documentation gives an example with two hooks in Bash: one logs every command to ~/.claude/bash.log and another denies commands with rm -rf. All matching hooks run to completion before Claude Code aggregates the results, and the most restrictive response wins, in the order deny, defer, ask, allow. That is, a deny does not prevent the other hooks from executing. The log continues to be written.
Hook, deny rule, or CLAUDE.md: which to use
Each layer has a different role, and using just one leaves gaps:
- CLAUDE.md: guides the model. Great for conventions, but depends on the agent following the instruction.
- Hook PreToolUse: applies your rule, in code, before the call. Useful for path and command patterns you can describe with a script.
- permissions.deny: denies by path rule, no script, directly in configuration.
- Sandbox: limits where shell commands can write, covering what the other layers don't reach.
A good order to start: hook for files that should never change, deny rule to reinforce, and sandbox if the project handles real secrets.
When to combine with other protections
If you run more than one agent in the same repository, it's worth stacking layers. The tutorial on Claude Code and Codex together in the same repository shows how to isolate each agent in a worktree, and the one on sandbox and approvals in Codex CLI covers the equivalent in Codex.
Frequently asked questions about the Claude Code PreToolUse hook
What is the difference between exit 0 and exit 2 in a hook?
Exit 2 blocks the action and sends whatever is on stderr to Claude as feedback. Exit 0 means no objection, but in a PreToolUse it does not approve the call: it follows the normal permission flow.
Does the hook on Edit|Write prevent any changes to .env?
Not entirely. Claude can still modify files via shell commands. The documentation recommends adding Edit rules to permissions.deny and configuring the sandbox to limit where commands can write.
Does a hook that denies prevent other hooks from running?
No. All matching hooks run to completion before Claude Code combines the results. The most restrictive decision wins, in the order deny, defer, ask, allow.
Do I need to make the script executable?
Yes, on macOS and Linux. Without execute permission, Claude Code cannot run the script. Use chmod +x .claude/hooks/protect-files.sh.
Conclusion
A few lines of script and a block in settings.json turn "please don't touch .env" into a rule that Claude Code applies before the edit. Register the hook, test with a real request, and remember the limit: shell commands require permissions.deny rules and sandbox as extra layers.
Related articles

Claude Code: 3 hooks for desktop alerts, auto-formatting with Prettier, and context retention
Configure three hooks in Claude Code: desktop alerts when the agent waits for you, automatic Prettier after every edit, and context re-injection after compaction.

How to use Claude Code and Codex together in the same repository without conflicts
Step-by-step guide to running Claude Code and Codex CLI in the same project: one implements in an isolated worktree while the other reviews in read-only mode, without stepping on each other's files.

How to test Gemini 4 Hydrogen today: access, pricing, and tasks
Access Gemini 4 Hydrogen today, understand the pricing, and see the tasks to test.
