brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: block edits to .env with a PreToolUse hook that exits 2

Security
~/tips/tip-claude-hook-pretooluse-protect-files

exit 2

Blocks Claude Code from editing protected files by running a script that exits with code 2.

CLAUDE.md is a polite request. A PreToolUse hook is a locked door.

A PreToolUse hook runs before a tool call and can block it. The docs example is a small script that reads the target path from stdin and exits with code 2 when it matches a protected pattern. The message you print to stderr goes back to Claude.

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
for pattern in ".env" "package-lock.json" ".git/"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches '$pattern'" >&2
    exit 2
  fi
done
exit 0

Save it as .claude/hooks/protect-files.sh, run chmod +x on it, and register it under PreToolUse with the matcher Edit|Write, using "$CLAUDE_PROJECT_DIR"/.claude/hooks/protect-files.sh as the command.

Settings deny rules decide what Claude may do, and a hook adds your own logic on top, like a custom pattern list or a log line. Start with the three patterns from the example and extend the list when a file worries you.

The caveat: hook scripts must be executable or they will not run. And this watches Claude’s edit tools, not every way a file can change. The memory docs say the same thing in other words: CLAUDE.md is context, a hook is what enforces.

Further reading: Automate actions with hooks – Claude Code docs, How Claude remembers your project – Claude Code docs, On this site: let a PostToolUse hook run Prettier after every Claude edit, On this site: add a Notification hook so Claude Code pings you when it waits

More Security tips tcpdump -nn -r capture.pcap port 53 mkcert -install Strict-Transport-Security: max-age=0 Referrer-Policy: strict-origin-when-cross-origin wp super-admin list All Security tips (79) All topics

Link