A line in CLAUDE.md says: never edit .env. The model reads it, agrees, and then, three tool calls later, writes a test fixture to .env because that seemed like the shortest path. Instructions influence a model. They do not constrain it.
Claude Code has two mechanisms that do constrain it. Permission rules decide whether a tool may run at all. Hooks run your own shell commands at lifecycle points and can block a call before it happens. This tutorial builds a small PreToolUse hook that rejects writes to secrets and a few destructive shell commands, then tests it without involving the model.
The examples use Claude Code's documented hook contract: the hook receives JSON on standard input, and exit code 2 blocks the tool call and sends the message on standard error back to Claude.
Step 1 — write a guard that reads JSON
Create .claude/hooks/guard.sh. It reads tool_name and the relevant field from tool_input: file_path for Edit and Write, command for Bash.
#!/usr/bin/env bash
set -euo pipefail
input=$(cat)
tool=$(printf '%s' "$input" | jq -r '.tool_name // empty')
path=$(printf '%s' "$input" | jq -r '.tool_input.file_path // empty')
command=$(printf '%s' "$input" | jq -r '.tool_input.command // empty')
block() {
printf 'blocked (%s): %s\n' "$tool" "$1" >&2
exit 2
}
case "$path" in
*.env|*/.env|*/.env.*|*/.git/*|*/node_modules/*)
block "protected path: $path" ;;
esac
case "$command" in
*"git push --force"*|*"git push -f"*|*"rm -rf /"*|*"| sh"*|*"| bash"*)
block "dangerous command: $command" ;;
esac
exit 0Make it executable with chmod +x .claude/hooks/guard.sh. The script needs jq; install it with your package manager if the command is missing.
Two details matter. First, an exit code of 2 is the blocking signal. Any other non-zero exit is reported as an error but does not block the call. Second, the message goes to standard error, which is how Claude learns why the action failed.
Step 2 — register it for Bash, Edit and Write
Add the hook to .claude/settings.json so it travels with the repository. Use ~/.claude/settings.json only for personal guards you do not want to share.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Edit|Write",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/guard.sh"
}
]
}
]
}
}The matcher selects tool names. Bash|Edit|Write covers the three paths this guard understands. If you use a different edit tool or an MCP server with write access, add it deliberately rather than widening the matcher to everything.
Inside a session, /hooks opens a read-only view of what is loaded. Edit the JSON file to change it; do not expect the menu to be an editor.
Step 3 — test the script without the agent
Hooks fail open in the worst way: a typo can make the guard exit 0 for everything. Test the contract directly before trusting it.
printf '%s' '{"tool_name":"Write","tool_input":{"file_path":".env"}}' \
| .claude/hooks/guard.sh
echo "exit=$?" # expect 2
printf '%s' '{"tool_name":"Bash","tool_input":{"command":"git status"}}' \
| .claude/hooks/guard.sh
echo "exit=$?" # expect 0Run the same check for a force push and for a safe npm test. If the environment file case exits 0, the JSON field name is probably wrong. Print the parsed values while debugging, but remove the debug output before committing: the hook receives file paths and commands that may contain sensitive data.
Step 4 — verify inside a session
Ask Claude to add a line to .env. The write should be refused, and Claude should see the reason from standard error. Then ask it to run git status; that should proceed normally. Test a force push only in a throwaway repository.
If the hook does not fire, check three things: the settings file is in the project root, the matcher matches the tool name exactly, and the command path resolves. $CLAUDE_PROJECT_DIR avoids depending on the current working directory.
Step 5 — combine it with permission rules
Hooks are one layer. Permission rules are another. Claude Code evaluates deny rules before ask and allow rules, so a deny rule is the right place for a hard boundary such as Bash(rm *) or a tool you never want available. Hooks are better for context-dependent checks: this path, this command pattern, this repository.
Use both. A deny rule removes a capability. A hook explains a policy and can inspect arguments that a static rule cannot express.
What hooks do not solve
A hook runs as your user, with your credentials. It is code execution, not a sandbox. Anyone who can edit .claude/settings.json can disable it. For organization-wide enforcement, distribute hooks and permission rules through managed settings instead of relying on each repository.
The guard also needs maintenance. New file layouts, new package managers and new tools create new paths. Review the patterns when you add a connector or a workflow, and keep a test for every rule that protects something irreversible. The goal is not a perfect list of bad strings. It is a deterministic checkpoint that fails closed for the few actions you cannot undo.