Founders BetaFounder price: US$ 9.90/month locked for as long as you subscribe.→
HomeBlogDicasClaude Code: how to block edits to .env and protected files with a hook
Official Claude Code changelog
Image: Anthropic / changelog do Claude Code
Dicas6 min

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.

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.

The biggest AI newsletter in the World

Get AI articles in your inbox

Technical curation on models, agents and coding tools. No spam, unsubscribe anytime.

Daily at 8:00 and 16:00 Brasília time. No spam.

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, the command field 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:

Terminal
#!/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 0

The 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:

Terminal
chmod +x .claude/hooks/protect-files.sh

Step 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:

JSON
{
  "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:

Terminal
#!/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ões

Register 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.

Source: Hooks reference, Claude Code Docs

Share this article

Tags:#claude-code#hooks#segurança#pretooluse#dicas
Marcelo Santiago
Marcelo Santiago·Creator of bridgecode

Developer and creator of bridgecode, an agentic development environment for orchestrating squads of AI agents. Helps people going from vibe coding to professional development move from idea to shipped product.

The biggest AI newsletter in the World

Enjoyed this content? Stay ahead in AI engineering.

Code analysis, multi-agent architecture, token benchmarks and tools selected by developers for developers.

Daily at 8:00 and 16:00 Brasília time. No spam.