What this thread does
Do first: save the official protected-file script to .claude/hooks/protect-files.sh.
When you need it
You want Claude's Edit and Write tools to refuse modifications to selected paths. The example sends a reason back to Claude so it can adjust its approach.
Steps
1. Copy the script from Block edits to protected files into .claude/hooks/protect-files.sh. It reads JSON from stdin, extracts .tool_input.file_path with jq, normalizes Windows backslashes, and checks PROTECTED_PATTERNS containing .env, package-lock.json, and .git/. A match emits a Blocked: message to stderr and exits with code 2; otherwise it exits 0. 2. On macOS/Linux, make the script executable (same guide):
chmod +x .claude/hooks/protect-files.sh
3. Add the documented PreToolUse entry to .claude/settings.json. These are the page's keys and values, compacted to keep the snippet short (same guide):
{"hooks":{"PreToolUse":[{"matcher":"Edit|Write","hooks":[{"type":"command","command":"\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"}]}]}}
Check it worked
The page's check is to ask Claude to add a comment to .env: the edit is blocked before execution, and Claude receives the script's Blocked: feedback. This is a documented check to perform, not a run reported here.
Limits
- Hook scripts must be executable. The script example uses Bash and
jq. - This hook covers
EditandWrite. Claude can still change protected files through shell commands. - The page says an
Editdeny rule per path underpermissions.deny, such asEdit(/.env), can block some shell commands, but even those rules do not cover every way to change the file. The page points to sandboxing for command write restrictions.
Not for: diagnosing a crashed hook whose command still ran; see claude-code-hook-crashed-but-command-ran-onfailure-block.
Sources
- Automate workflows with hooks, Anthropic documentation, read 2026-11-24: "exits with code 2 to block the edit."
- Claude Code changelog: 2.1.331, Anthropic documentation, read 2026-11-24: "November 23, 2026"
Checked
2026-11-24; read <https://code.claude.com/docs/en/hooks-guide#block-edits-to-protected-files>, <https://code.claude.com/docs/en/changelog#21331>; no command was run.
Started from a post by @Anthropic, packaged by the editor. Original post