SmartScope · Generative AI
Claude Code hooks: Using stdin JSON and jq to Control Prettier and Block rm -rf

Claude Code hooks allow you to execute external commands during lifecycle events by parsing JSON passed via standard input (stdin) using tools like jq instead of environment variables. Based on the official documentation, this guide details running Prettier after file edits, blocking dangerous commands with PreToolUse, choosing notification events, and troubleshooting configuration issues.
On this page
- The Role of Claude Code Hooks and Differences from CLAUDE.md and Skills
- PostToolUse Configuration to Run Prettier After File Edits
- Stopping rm -rf with PreToolUse, Exit Codes, and JSON Control
- Choosing Between Stop and Notification to Alert on Response Completion and Idle Input
- Where to Place settings.json and How to Troubleshoot Non-Working Hooks
- Sources
If you want to automate code formatting after file edits, block the execution of dangerous commands, or automate notifications upon response completion in Claude Code, hooks are the ideal solution. Hooks provide a mechanism to intercept various events throughout the Claude Code lifecycle. Because input values are delivered as JSON to standard input (stdin) rather than through dedicated environment variables, you extract file paths or command strings using CLI tools like jq to invoke your target processes.
To use hooks, your execution environment must have the necessary CLI tools installed in advance, such as Bash, jq, and Prettier. Furthermore, because hooks execute local scripts with the user's permissions, you must verify the safety of any script before registering it.
If you want to check your configuration immediately, add your settings to .claude/settings.json in the root of your project and run the /hooks command inside Claude Code to confirm that the settings have been loaded.
This article reflects information as of JST. The information may have been updated since then; check the official source for the latest.
The Role of Claude Code Hooks and Differences from CLAUDE.md and Skills
CLAUDE.md, Skills, and hooks all adjust how Claude Code operates, but they differ in purpose and enforcement power. CLAUDE.md consists of natural language prompts designed to communicate instructions and context to Claude; it cannot enforce external command execution or deterministically intercept processes. Skills define extended tools that Claude can call as needed. In contrast, hooks automatically and deterministically enforce the execution of specified external processes in response to events such as tool execution, session starts, or response completion.
According to official documentation, there are five handler types: command (runs external commands), http (sends JSON via HTTP POST), mcp_tool (calls tools on configured MCP servers), prompt (performs single-turn model evaluations), and agent (uses a verification subagent). Among these, agent is noted as an experimental feature. Not all five handler types are available for every event. For example, PermissionRequest does not support agent, and mcp_tool is skipped during SessionStart and Setup because MCP connections are unavailable immediately after startup or during setup processing. When implementing formatting or safety controls via local scripts, you will primarily use the command handler. Official Reference
As of this writing, 33 lifecycle events are documented in the official materials. The primary events, their triggers, and supported handlers are as follows:
| Event Name | Main Trigger | Supported Handlers |
|---|---|---|
| PreToolUse | Before tool execution: evaluate whether to allow execution or modify inputs | All 5 types (command, http, mcp_tool, prompt, agent) |
| PostToolUse | After successful tool execution: post-processing or feedback | All 5 types |
| PermissionRequest | When permission decisions are required for tool execution | command, http, mcp_tool, prompt (agent not supported) |
| Stop | When Claude finishes generating a response (end of each turn) | All 5 types |
| Notification | When Claude Code issues a notification (permission requests, idle states, etc.) | command, http, mcp_tool (prompt, agent not supported) |
| SessionStart | When a session starts or resumes | command, mcp_tool (skipped if MCP is not connected) |
The input data received by a command hook is a JSON string delivered via standard input (stdin), not environment variables. Environment variables mentioned in unofficial guides, such as $CLAUDE_TOOL_INPUT_FILE_PATH or $TOOL_INPUT, are not guaranteed by the official documentation. In addition to common fields such as session_id, cwd, transcript_path, and hook_event_name, the stdin JSON includes tool-specific fields like tool_name and tool_input, as well as tool_response in PostToolUse. Official Reference
PostToolUse Configuration to Run Prettier After File Edits
To run a code formatter like Prettier immediately after Claude Code modifies a file, combine the PostToolUse event with a matcher. PostToolUse fires after a tool executes successfully. By specifying Edit|Write in the matcher, you can trigger the hook only when file creation or editing tools are called. However, this configuration triggers only when Claude Code itself executes the Edit or Write tool; it does not detect file modifications made via Bash or direct saves in external editors. Comprehensive monitoring of changes on disk requires alternative mechanisms such as the FileChanged event. Official Guide
In the .claude/settings.json configuration file, specify the external script path using the exec format with command and an args array. Using an argument array prevents issues where arguments might be split incorrectly if project paths contain spaces.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "bash",
"args": [
"${CLAUDE_PROJECT_DIR}/.claude/hooks/format-after-edit.sh"
]
}
]
}
]
}
}
Inside the invoked script, parse the JSON passed via stdin using the jq command to extract .tool_input.file_path. Enclose the extracted file path variable in double quotes and pass it to Prettier. Additionally, redirect messages and error output to standard error (stderr) so formatter outputs are not confused with control instructions for Claude Code. An example configuration based on official specifications is as follows:
#!/bin/bash
FILE_PATH=$(jq -r '.tool_input.file_path') || exit 1
if [ -z "$FILE_PATH" ] || [ "$FILE_PATH" = "null" ]; then
printf '%s\n' 'Missing tool_input.file_path' >&2
exit 1
fi
npx prettier --write "$FILE_PATH" >&2
To use this configuration, your environment must have Bash, jq, Node.js, and your project-specific Prettier installed. Furthermore, because PostToolUse runs after tool execution, it can format code but cannot undo modifications that have already been applied. Official Guide
Stopping rm -rf with PreToolUse, Exit Codes, and JSON Control
If you want to prevent destructive commands such as accidental file deletion before they run, use the PreToolUse event to intervene prior to tool execution. Specify Bash in the matcher and evaluate the string contained in .tool_input.command from the input JSON. There are two ways to block actions in PreToolUse: controlling execution via the script's exit code, or returning a specific JSON payload to standard output and exiting with code 0. Official Reference
Returning exit code 2 immediately blocks tool execution in PreToolUse. In this case, any text written to standard error (stderr) is treated as the reason for blocking shown to both the user and Claude. Additionally, configuring "onFailure": "block", available in Claude Code v2.1.295 and later, prevents tool execution from proceeding if the script crashes or times out. Because hooks intended for security control must run synchronously, do not specify "async": true. Official Reference
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash",
"args": [
"${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm-rf.sh"
],
"onFailure": "block"
}
]
}
]
}
}
#!/bin/bash
COMMAND=$(jq -r '.tool_input.command') || exit 2
case "$COMMAND" in
*'rm -rf'*)
printf '%s\n' 'Blocked by hook: rm -rf' >&2
exit 2
;;
esac
exit 0
When controlling execution via JSON output, you must emit valid JSON to standard output (stdout) and terminate the script with exit code 0. Note that the required JSON structure differs between PreToolUse and PermissionRequest. The differences in behavior for each control method are as follows:
| Target | Method | Output and Exit Code | Behavior |
|---|---|---|---|
| PreToolUse | Exit code | Output reason to stderr and exit 2 | Blocks command execution. PreToolUse exit 2 cannot be overridden by JSON allow. |
| PreToolUse | JSON (deny) | Output {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"reason"}} to stdout and exit 0 |
Denies tool execution. |
| PreToolUse | JSON (ask) | Set permissionDecision to "ask" and exit 0 |
Displays an interactive confirmation prompt to the user. |
| PreToolUse | JSON (allow) | Set permissionDecision to "allow" and exit 0 |
Bypasses the permission confirmation prompt. However, constraints such as deny/ask rules remain. |
| PermissionRequest | JSON | Output {"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"deny","message":"reason"}}} to stdout and exit 0 |
Denies permission request. In PermissionRequest, denial via exit 2 is invalid. |
The script above is a simplified example that checks whether rm -rf is contained within the supplied command string. It does not comprehensively block variations in option order (such as rm -f -r), command aliases, alternative deletion commands, or complex expressions involving shell variable expansions. Furthermore, because verification involving the execution of destructive commands was not conducted, thorough validation tailored to your specific project is required before production use. Official Reference
Choosing Between Stop and Notification to Alert on Response Completion and Idle Input
If you want to receive OS notifications based on Claude Code's processing state, choose between the Stop event and Notification event depending on your notification goals.
The Stop event fires after every turn in which Claude finishes generating a response message. Stop does not guarantee the completion of the overall task. If Claude asks a clarifying question midway through, or even in the middle of a multi-step task, Stop executes whenever an individual response turn concludes. Furthermore, if the user manually interrupts the process, Stop does not fire; if an interruption occurs due to an API error or similar issue, the StopFailure event fires instead. Official Reference
To detect and notify when the system is waiting for user input, use the Notification event. Notification supports notification types via matcher; if left blank or unspecified, it matches all types. To narrow down to specific situations, specify a matcher. For example, idle_prompt fires when there is no user input for approximately 60 seconds after Claude's response, and permission_prompt fires when user permission is requested to run a tool. Official Guide
| Event / matcher | Primary Trigger Timing | Recommended Use Case |
|---|---|---|
| Stop | When response output concludes normally for each turn | When you want to know that Claude has finished speaking during work |
| Notification (unspecified) | All situations where Claude Code issues a notification | When you want to receive all alerts, including permission prompts and waiting states |
| Notification (idle_prompt) | When there is no input for approximately 60 seconds after response completion | When you want to prevent leaving the session idle after forgetting to enter the next instruction |
| Notification (permission_prompt) | When waiting for user approval to execute a tool | When you want to notice that processing has stopped waiting for permission confirmation |
The command used to send notifications differs across operating systems. Common choices are osascript on macOS and notify-send on Linux. For Windows, the official documentation provides an example using PowerShell's MessageBox; note that this behaves differently from native OS toast notifications. On macOS, displaying notifications from scripts requires notification permissions for applications such as Script Editor. Official Guide
Where to Place settings.json and How to Troubleshoot Non-Working Hooks
Multiple configuration files can define hooks, each having a designated scope and precedence. You should properly separate shared team settings from settings limited to personal environments. Official Reference
| Configuration File Location | Scope | Use Case |
|---|---|---|
~/.claude/settings.json |
User-wide environment | Notifications and environment-dependent hooks to be used across all projects |
.claude/settings.json |
Shared project | Formatting settings committed to the repository and shared across the entire team |
.claude/settings.local.json |
Individual project (personal) | Hooks enabled only on an individual development machine, excluded from the repository |
| Managed Policy (Managed) | Organization-wide | Hooks enforced by administrators; cannot be disabled from individual settings |
Hooks defined at each configuration level do not overwrite or delete one another; instead, they are merged additively. Note that even if disableAllHooks: true is configured in user or project settings to disable all hooks, hooks defined by organizational managed policies cannot be disabled. Official Reference
When hooks do not function as expected, isolate the issue using the following steps:
- Check registration status: Run the
/hookscommand within Claude Code and inspect the displayed output. This screen is a read-only UI displaying the list of configured hooks, their origins, event names, and matchers. If settings are not reflected, verify file paths and JSON syntax, then restart the session. - Unit test input data: Confirm whether the script works in isolation. Prepare a test JSON payload like the one below, pipe it to the script's stdin, and execute it. Separately verify that the exit code, stdout, and stderr match expectations.
- Separate output and verify shell configuration: For scripts outputting control JSON to stdout,
echostatements in shell startup files (such as.bashrc) can contaminate stdout and cause JSON evaluation to be ignored. Direct all informative messages to stderr (>&2). - Output debug logs: Launch Claude Code with
claude --debugorclaude --debug-fileto inspect hook execution logs and error outputs. - Check managed policies: In organizational environments where
allowManagedHooksOnlyis enabled, personal and project local hooks are neither loaded nor executed. Official ReferenceOfficial Guide
An example test JSON structure used for unit testing is as follows:
{
"session_id": "example-session",
"transcript_path": "/tmp/example-transcript.jsonl",
"cwd": "/tmp/demo-project",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {
"command": "rm -rf /tmp/example-only"
},
"tool_use_id": "example-tool-call"
}
Sources
Last verified: October 21, 2026
Read next: Claude & Claude Code · How to use
- Denied by the Claude Code auto mode classifier: 3 Ways to Allow It
- Claude: Auto Mode Default Changes Starting Next Week and How to Switch Back to Manual
- Anthropic: Mathematician Claims Proof of Riemann Hypothesis with Claude



