Files
claude-howto/06-hooks/pre-tool-check.sh
yarlinghe bce7cf8cb4 fix(hooks): correct pre-tool-check.sh hook protocol bugs (#72)
The pre-tool-check.sh example had three bugs rooted in the same
misunderstanding of the Claude Code PreToolUse hook protocol
(stdin/stdout/stderr + exit code contract):

1. Substring matching on `rm -rf /`
   The pattern was unanchored, so grep treated it as a substring and
   falsely blocked any command containing `rm -rf /` — including benign
   calls like `rm -rf /tmp/build` or `rm -rf /var/cache/foo`. Fixed by
   anchoring the slash to a whitespace-or-end-of-line boundary.

2. WARN tier was dead code
   The warning layer printed to stderr and then `exit 0`. Claude Code
   silently discards stderr on exit 0, so the warnings were never seen
   by Claude, the user, or any log. Fixed by adding an audit log file
   at `$CLAUDE_PROJECT_DIR/.claude/hooks/audit.log` that records every
   invocation with its decision (BLOCK/WARN/ALLOW). The audit log is
   now the reliable observability mechanism for the WARN tier.

3. BLOCK reasons printed to stdout instead of stderr
   On `exit 2`, Claude Code reads stderr to surface the block reason
   to Claude. The echoes before `exit 2` defaulted to stdout, so
   Claude Code reported `"No stderr output"` and Claude had to read
   the hook source file to infer why a command was blocked. Fixed by
   explicitly redirecting the block-reason echoes to stderr with `>&2`.

Also escaped the regex metacharacters in the fork-bomb pattern
`:(){:|:&};:` so it matches literally under `grep -E`, and updated the
header docstring to document the stdout/stderr/exit-code convention so
future readers don't make the same mistakes.

Verified with 6 smoke tests covering: benign command (ALLOW), warn-tier
relative path, substring edge case (`rm -rf /tmp/...` no longer falsely
blocked), exact root match (`rm -rf /`, `rm -rf / ; echo` still blocked),
fork-bomb literal, and `git push --force` (WARN only). stdout is empty
in all cases; all reasons correctly routed to stderr or the audit log.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 22:48:05 +02:00

4.9 KiB