Skip to contentমূল লেখায় যান

Part 12পর্ব 12 · Extend

Hooks

A hook runs your own code at a fixed point in a Claude Code session, whatever Claude decides. This page shows how a hook gets its input, how it blocks an action, and four QA hooks: protect files, format after edits, run tests after edits, and log shell commands.

15 min read15 মিনিটে পড়া যায় · 11 sections11টি সেকশন · 5 sources5টি সোর্স · updated Nov 2026আপডেট: Nov 2026

A hook blocks what CLAUDE.md cannotহুক যা ব্লক করে, CLAUDE.md তা পারে না

Try to edit .env and see a hook deny it before the tool runs. Then change where the rule lives..env এডিট করার চেষ্টা করুন আর দেখুন টুল চলার আগেই হুক সেটা আটকায়। তারপর নিয়মটা কোথায় থাকে তা বদলান।

2 min2 মিনিট7 steps7টি ধাপ
  • Hook runsহুক চলা4 / 4
  • Blockedব্লক হয়েছে2 / 4
  • Protected files changedবদলানো সুরক্ষিত ফাইল0 / 2
ClaudeClaudePreToolUsePreToolUsehookহুকEditEdittoolটুল.env.envCLAUDE.md: no .envCLAUDE.md: .env নয়Edit .envএডিট .env

You’ll learnআপনি শিখবেন

  • A rule in CLAUDE.md is text, not a blockCLAUDE.md-এর নিয়ম শুধু লেখা, ব্লক নয়✓
  • What the matcher Edit|Write selectsম্যাচার Edit|Write কী বেছে নেয়
  • Exit 2 blocks the tool, exit 1 does notExit 2 টুল ব্লক করে, exit 1 করে না
  • Why to add deny rules for BashBash-এর জন্য কেন deny রুল লাগে

What hooks are

Hooks are user-defined handlers that run automatically at specific points in the Claude Code lifecycle. A handler can be a shell command, an HTTP endpoint, an MCP tool call, an LLM prompt, or a subagent. Source 1সোর্স 1

  • Some events happen once per session (SessionStart, SessionEnd), some once per turn (UserPromptSubmit, Stop), and some on every tool call (PreToolUse, PostToolUse). Source 1সোর্স 1
  • If Claude skips a rule that must hold every time, move the rule into a hook. Source 2সোর্স 2

Don'tকরবেন না: A hard rule only in CLAUDE.md

"Never edit .env" in CLAUDE.md is context that Claude reads. It is not a block. See CLAUDE.md & Memory.

Doকরুন: A hard rule in a hook

A PreToolUse hook that returns permissionDecision: "deny" blocks the tool, even in bypassPermissions mode. Source 3সোর্স 3

সহজ English

A hook is your own handler. Claude Code runs it automatically at a fixed point in a session. A handler can be a shell command, an HTTP endpoint, an MCP tool call, an LLM prompt, or a subagent. Source 1সোর্স 1

Some points come one time per session (SessionStart, SessionEnd). Some come one time per turn (UserPromptSubmit, Stop). Some come on every tool call (PreToolUse, PostToolUse). Source 1সোর্স 1

If Claude skips a rule that must hold every time, move the rule into a hook. Source 2সোর্স 2 The rule "Never edit .env" in CLAUDE.md is only text that Claude reads. It does not block anything. A PreToolUse hook that returns permissionDecision: "deny" blocks the tool, even in bypassPermissions mode. Source 3সোর্স 3

বাংলা ব্যাখ্যা

Hook হলো আপনার নিজের একটি handler। Claude Code একটি session-এর নির্দিষ্ট কিছু সময়ে এটি নিজে থেকেই চালায়। Handler হতে পারে একটি shell command, একটি HTTP endpoint, একটি MCP tool call, একটি LLM prompt অথবা একটি subagent। Source 1সোর্স 1

কিছু event প্রতি session-এ একবার ঘটে (SessionStart, SessionEnd), কিছু প্রতি turn-এ একবার (UserPromptSubmit, Stop), আর কিছু প্রতিটি tool call-এ (PreToolUse, PostToolUse)। Source 1সোর্স 1

যে নিয়ম প্রতিবার মানতেই হবে, Claude যদি সেটি বাদ দেয়, তাহলে নিয়মটি একটি hook-এ নিয়ে যান। Source 2সোর্স 2 CLAUDE.md-এ লেখা "Never edit .env" শুধু context, যা Claude পড়ে। এটি কিছু block করে না। কিন্তু যে PreToolUse hook permissionDecision: "deny" ফেরত দেয়, সেটি tool-টিকে block করে, এমনকি bypassPermissions mode-এও। Source 3সোর্স 3

How a hook is built

A hook configuration has three levels: an event, a matcher group, and one or more handlers. Source 1সোর্স 1 This is the minimal structure: Source 1সোর্স 1

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "./scripts/after-edit.sh" }
        ]
      }
    ]
  }
}

Where hooks live

LocationScope
~/.claude/settings.jsonAll your projects Source 1সোর্স 1
.claude/settings.jsonOne project. You can commit it. Source 1সোর্স 1
.claude/settings.local.jsonOne project. Not shared. Source 1সোর্স 1
Managed policy settingsThe organization Source 1সোর্স 1
Plugin hooks/hooks.jsonWhere the plugin is enabled Source 1সোর্স 1
Skill frontmatterThe rest of the session after the skill is used Source 1সোর্স 1
Subagent frontmatterWhile that subagent runs Source 1সোর্স 1

The Settings & the .claude Folder page explains the settings files.

Matchers

The matcher selects which tool calls (or other event sources) trigger the hook. Source 1সোর্স 1

MatcherMatches
"*", "", or no matcherEverything Source 1সোর্স 1
Edit|Write or Edit, WriteExactly Edit or Write Source 1সোর্স 1
Edit.*A regular expression. It also matches NotebookEdit. Source 1সোর্স 1
mcp__atlassian__.*Every tool of the MCP server named atlassian Source 1সোর্স 1
  • A matcher with only letters, digits, _, -, spaces, ,, and | is an exact name or a list of names. Any other character makes it a JavaScript regular expression. Source 1সোর্স 1
  • Matchers are case-sensitive. Source 3সোর্স 3
  • MCP tool names have the form mcp__<server>__<tool>. A bare mcp__atlassian matches nothing in a hook matcher. Add __.*. Source 1সোর্স 1
  • For tool events, the matcher tests the tool name. For other events it tests something else, for example the session start source for SessionStart. A matcher on an event without matcher support is ignored. Source 1সোর্স 1

Common mistake: matching only Write

The old example on this page used the matcher Write. That misses every Edit. Use Edit|Write for file changes. Source 1সোর্স 1

সহজ English

A hook configuration has three levels: an event, a matcher group, and one or more handlers. Source 1সোর্স 1

You can put hooks in many places. ~/.claude/settings.json is for all your projects. .claude/settings.json is for one project, and you can commit it. .claude/settings.local.json is for one project and is not shared. Hooks can also come from managed policy settings, a plugin, a skill, or a subagent. Source 1সোর্স 1 Hooks from different settings levels merge. They do not replace each other. All matching hooks run in parallel. The same handler in two settings files runs one time. Source 1সোর্স 1 Claude Code normally applies hook edits automatically. If it does not, restart the session. Source 1সোর্স 1 Source 3সোর্স 3

The matcher selects which tool calls start the hook. "*", "", or no matcher matches everything. Edit|Write matches exactly Edit or Write. Other characters, as in Edit.*, make the matcher a regular expression. For an MCP server, use a form such as mcp__atlassian__.*. Source 1সোর্স 1 Matchers are case-sensitive. Source 3সোর্স 3 For file changes, use Edit|Write, not only Write. Source 1সোর্স 1

বাংলা ব্যাখ্যা

একটি hook configuration-এর তিনটি স্তর আছে: একটি event, একটি matcher group এবং এক বা একাধিক handler। Source 1সোর্স 1

Hook অনেক জায়গায় রাখা যায়: ~/.claude/settings.json (আপনার সব project), .claude/settings.json (একটি project, commit করা যায়) এবং .claude/settings.local.json (একটি project, share হয় না)। এছাড়া managed policy settings, plugin-এর hooks/hooks.json, skill frontmatter অথবা subagent frontmatter থেকেও hook আসতে পারে। Source 1সোর্স 1 বিভিন্ন settings level-এর hook একসাথে merge হয়, একটি অন্যটিকে replace করে না। মিলে যাওয়া সব hook parallel-এ চলে, আর একই handler একাধিক settings file-এ থাকলে একবারই চলে। Source 1সোর্স 1 Claude Code সাধারণত hook-এর পরিবর্তন নিজে থেকেই প্রয়োগ করে। না করলে session restart করুন। Source 1সোর্স 1 Source 3সোর্স 3

matcher ঠিক করে কোন tool call hook-টি চালাবে। "*", "" অথবা কোনো matcher না থাকলে সবকিছু মেলে। Edit|Write ঠিক Edit বা Write-কে মেলায়। অন্য character থাকলে, যেমন Edit.*-এ, matcher-টি একটি regular expression হয়ে যায়। MCP server-এর জন্য mcp__atlassian__.*-এর মতো রূপ ব্যবহার করুন। Source 1সোর্স 1 Matcher case-sensitive। Source 3সোর্স 3 File পরিবর্তনের জন্য শুধু Write নয়, Edit|Write ব্যবহার করুন। Source 1সোর্স 1

What your hook receives

A command hook gets the event data as JSON on stdin. An HTTP hook gets it as the body of a POST request. Source 1সোর্স 1 Example input for a PreToolUse hook on Bash, with only some fields: Source 1সোর্স 1

{
  "session_id": "abc123",
  "cwd": "/home/user/payment-service",
  "permission_mode": "default",
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": { "command": "npm test" },
  "tool_use_id": "toolu_01ABC123..."
}
  • Common fields include session_id, transcript_path, cwd, and hook_event_name. Most events also get permission_mode, but not all of them. Inside a subagent, the input also has agent_id and agent_type. Source 1সোর্স 1
  • For Write, tool_input has file_path and content. For Edit, it has file_path, old_string, and new_string. Source 1সোর্স 1
  • For Write, Edit, and Read, tool_input.file_path is always an absolute path. On Windows, it has backslashes. Source 1সোর্স 1
  • A PostToolUse hook also gets tool_response. Source 1সোর্স 1

Common mistake: $CLAUDE_FILE_PATH

The docs define no $CLAUDE_* tool environment variables such as CLAUDE_TOOL_NAME, CLAUDE_FILE_PATH, or CLAUDE_TOOL_INPUT. Source 1সোর্স 1 Source 3সোর্স 3 Source 4সোর্স 4 Read the tool data from stdin, for example with jq -r '.tool_input.file_path'.

Hook scripts do get some environment variables: CLAUDE_PROJECT_DIR, CLAUDE_EFFORT, and for plugin hooks CLAUDE_PLUGIN_ROOT and CLAUDE_PLUGIN_DATA. Source 1সোর্স 1 Source 4সোর্স 4

সহজ English

A command hook gets the event data as JSON on stdin. An HTTP hook gets the same data as the body of a POST request. Source 1সোর্স 1 The data has fields such as session_id, cwd, hook_event_name, and tool_input. For Write and Edit, tool_input.file_path is always an absolute path. A PostToolUse hook also gets tool_response. Source 1সোর্স 1

Do not use variables such as $CLAUDE_FILE_PATH. The docs do not define them. Source 1সোর্স 1 Source 3সোর্স 3 Source 4সোর্স 4 Read the tool data from stdin, for example with jq -r '.tool_input.file_path'.

Hook scripts do get some environment variables, for example CLAUDE_PROJECT_DIR. Source 1সোর্স 1 Source 4সোর্স 4 CLAUDE_PROJECT_DIR is the project root where the session started. It stays the same if Claude moves into a worktree. The cwd field follows Claude. Source 1সোর্স 1 Use the variable in quotes in script paths, and make the script executable with chmod +x. Source 3সোর্স 3

বাংলা ব্যাখ্যা

একটি command hook event-এর data stdin-এ JSON হিসেবে পায়। একটি HTTP hook একই data একটি POST request-এর body হিসেবে পায়। Source 1সোর্স 1 এতে session_id, cwd, hook_event_name এবং tool_input-এর মতো field থাকে। Write এবং Edit-এর জন্য tool_input.file_path সবসময় একটি absolute path। একটি PostToolUse hook tool_response-ও পায়। Source 1সোর্স 1

$CLAUDE_FILE_PATH-এর মতো variable ব্যবহার করবেন না। Docs এগুলো define করে না। Source 1সোর্স 1 Source 3সোর্স 3 Source 4সোর্স 4 Tool-এর data stdin থেকে পড়ুন, যেমন jq -r '.tool_input.file_path' দিয়ে।

তবে hook script কিছু environment variable পায়, যেমন CLAUDE_PROJECT_DIR। Source 1সোর্স 1 Source 4সোর্স 4 CLAUDE_PROJECT_DIR হলো সেই project root, যেখানে session শুরু হয়েছিল। Claude কোনো worktree-তে গেলেও এটি একই থাকে। JSON-এর cwd field Claude-কে অনুসরণ করে। Source 1সোর্স 1 Script path-এ variable-টি quote-এর মধ্যে ব্যবহার করুন, আর chmod +x দিয়ে script-টি executable করুন। Source 3সোর্স 3

What your hook can answer

Exit codes

Exit codeMeaningEffect
0SuccessFor most events, Claude does not see the stdout. On UserPromptSubmit, UserPromptExpansion, SessionStart, and PostModelSwitch, plain stdout becomes context for Claude. Source 1সোর্স 1
2Blocking errorOn PreToolUse, the tool call is blocked. Claude gets the stderr text as the reason. Source 1সোর্স 1
Any other, including 1Non-blocking errorFor most events, the action continues. The transcript shows the first line of stderr. Source 1সোর্স 1

Exit 1 does not block

Claude Code treats exit code 1 as a non-blocking error and continues the action, even though 1 is the usual Unix failure code. Source 1সোর্স 1 A hook that cannot start, for example because of a wrong path, is also a non-blocking error. The transcript shows a hook error notice with the interpreter's message. Watch for this notice on the first run of a policy hook. Source 1সোর্স 1 To make a failed hook block the action, set "onFailure": "block" on a command, http, or mcp_tool hook (Claude Code v2.1.295 or later; v2.1.328 or later for mcp_tool). Then Claude Code blocks the action when the hook cannot start, exits with a code other than 0 or 2, or times out. Source 1সোর্স 1 Test each blocking hook with sample input.

সহজ English

A hook answers with an exit code. Exit code 0 means success. Exit code 2 is a blocking error. On PreToolUse, it blocks the tool call, and Claude gets the stderr text as the reason. Any other code, including 1, is a non-blocking error. For most events, the action continues. Source 1সোর্স 1 A hook that cannot start, for example because of a wrong path, also does not block. To make a failed hook block the action, set "onFailure": "block" on a command, http, or mcp_tool hook (Claude Code v2.1.295 or later; v2.1.328 or later for mcp_tool). Source 1সোর্স 1 Test each blocking hook with sample input.

Exit code 2 wins over JSON output. Source 1সোর্স 1 On PostToolUse, the tool already ran, so the hook cannot undo the action. Source 1সোর্স 1 Source 3সোর্স 3

বাংলা ব্যাখ্যা

Hook একটি exit code দিয়ে উত্তর দেয়। Exit code 0 মানে success। Exit code 2 হলো blocking error: PreToolUse-এ tool call block হয়, আর Claude stderr-এর লেখাটি কারণ হিসেবে পায়। 1-সহ অন্য যেকোনো code হলো non-blocking error। বেশিরভাগ event-এ action চলতে থাকে। Source 1সোর্স 1 যে hook শুরুই হতে পারে না (যেমন ভুল path-এর কারণে), সেটিও block করে না। Failed hook দিয়ে action block করাতে একটি command বা http hook-এ "onFailure": "block" set করুন (Claude Code v2.1.295 বা পরের version; mcp_tool-এর জন্য v2.1.328 বা পরের)। Source 1সোর্স 1 প্রতিটি blocking hook sample input দিয়ে test করুন।

Exit code 2 JSON output-এর চেয়ে অগ্রাধিকার পায়। Source 1সোর্স 1 PostToolUse-এ tool আগেই চালানো হয়ে গেছে, তাই hook action-টি undo করতে পারে না। Source 1সোর্স 1 Source 3সোর্স 3

JSON output

For finer control, exit 0 and print one JSON object on stdout. Do not mix the JSON with other text. Source 1সোর্স 1 A PreToolUse hook puts its decision in hookSpecificOutput: Source 1সোর্স 1

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Database writes are not allowed"
  }
}

Hooks and permission rules

  • A hook that returns deny blocks the tool even in bypassPermissions mode and with --dangerously-skip-permissions. Source 3সোর্স 3
  • A hook that returns allow does not bypass deny and ask rules from your settings. A blocking hook wins over allow rules. Source 5সোর্স 5
  • Files that you add with @ in a prompt fire no PreToolUse hook, not even one that matches Read. Use a Read deny rule for them. Source 1সোর্স 1

সহজ English

For finer control, exit 0 and print one JSON object on stdout. A PreToolUse hook puts permissionDecision inside hookSpecificOutput. The values are allow, deny, ask, or defer. If hooks disagree, deny wins. Source 1সোর্স 1

A hook that returns deny blocks the tool even in bypassPermissions mode. Source 3সোর্স 3 A hook that returns allow does not bypass the deny and ask rules in your settings. Source 5সোর্স 5

বাংলা ব্যাখ্যা

আরও সূক্ষ্ম নিয়ন্ত্রণের জন্য exit 0 দিন এবং stdout-এ একটি JSON object print করুন। একটি PreToolUse hook permissionDecision রাখে hookSpecificOutput-এর ভেতরে। এর মান হতে পারে allow, deny, ask অথবা defer। Hook-গুলো একমত না হলে deny জেতে। Source 1সোর্স 1

যে hook deny ফেরত দেয়, সেটি bypassPermissions mode-এও tool block করে। Source 3সোর্স 3 যে hook allow ফেরত দেয়, সেটি আপনার settings-এর deny এবং ask rule bypass করে না। Source 5সোর্স 5

Events

The hooks reference documents 34 events. Source 1সোর্স 1 These are the events that QA work uses most:

EventWhen it runs
SessionStartWhen a session begins or resumes Source 1সোর্স 1
PreToolUseBefore a tool call executes. It can block the call. Source 1সোর্স 1
PostToolUseAfter a tool call succeeds Source 1সোর্স 1
PostToolUseFailureAfter a tool call fails Source 1সোর্স 1
StopWhen Claude finishes responding Source 1সোর্স 1
FileChangedUse it to catch a file that a Bash command or another process rewrote Source 1সোর্স 1

The full list is in the Reference.

সহজ English

The hooks reference documents 34 events. Source 1সোর্স 1 QA work uses these events the most: Source 1সোর্স 1

  • SessionStart: a session begins or resumes.
  • PreToolUse: before a tool call runs. It can block the call.
  • PostToolUse: after a tool call succeeds.
  • PostToolUseFailure: after a tool call fails.
  • Stop: Claude finishes its response.
  • FileChanged: use it to catch a file that a Bash command or another process rewrote.

The full list is in the Reference.

বাংলা ব্যাখ্যা

Hooks reference-এ 34টি event-এর বর্ণনা আছে। Source 1সোর্স 1 QA কাজে এই event-গুলো সবচেয়ে বেশি লাগে: Source 1সোর্স 1

  • SessionStart: session শুরু বা resume হলে।
  • PreToolUse: tool call চলার আগে। এটি call-টি block করতে পারে।
  • PostToolUse: tool call সফল হওয়ার পরে।
  • PostToolUseFailure: tool call fail করার পরে।
  • Stop: Claude উত্তর দেওয়া শেষ করলে।
  • FileChanged: কোনো Bash command বা অন্য process যে file আবার লিখেছে, তা ধরতে।

পুরো তালিকা Reference-এ আছে।

Hook types

typeWhat it does
commandRuns a shell command with the event JSON on stdin Source 1সোর্স 1
httpSends the JSON as a POST to url. To block, it returns a 2xx response with decision JSON. A status code alone cannot block. Source 1সোর্স 1
mcp_toolCalls a tool on an MCP server, with server, tool, and input Source 1সোর্স 1
promptSends the input to a Claude model for a single-turn yes/no decision Source 1সোর্স 1
agentStarts a subagent with tools. Agent hooks are experimental. Source 1সোর্স 1
  • PreToolUse, PostToolUse, Stop, and UserPromptSubmit are among the events that support all five types. SessionStart and Setup support only command and mcp_tool. Source 1সোর্স 1
  • Default timeouts: 600 s for command, http, and mcp_tool; 30 s for prompt; 60 s for agent. Source 1সোর্স 1 On UserPromptSubmit, PreModelSwitch, and PostModelSwitch, the default for command, http, and mcp_tool is 30 s. On MessageDisplay, it is 10 s. Source 1সোর্স 1
  • A PreToolUse hook of type command, http, or mcp_tool that times out does not block the tool call. Source 1সোর্স 1

সহজ English

A hook has one of five types: Source 1সোর্স 1

  • command runs a shell command with the event JSON on stdin.
  • http sends the JSON as a POST to url. To block, it must return a 2xx response with decision JSON. A status code alone cannot block.
  • mcp_tool calls a tool on an MCP server.
  • prompt sends the input to a Claude model for one yes or no decision.
  • agent starts a subagent with tools. Agent hooks are experimental.

Not all events support all five types. For example, SessionStart supports only command and mcp_tool. Source 1সোর্স 1 The default timeout is 600 s for command, http, and mcp_tool, 30 s for prompt, and 60 s for agent. Some events have shorter defaults. Source 1সোর্স 1 If a PreToolUse hook of type command, http, or mcp_tool times out, the tool call is not blocked. Source 1সোর্স 1

বাংলা ব্যাখ্যা

Hook-এর পাঁচটি type আছে: Source 1সোর্স 1

  • command: event JSON stdin-এ দিয়ে একটি shell command চালায়।
  • http: JSON-টি POST হিসেবে url-এ পাঠায়। Block করতে হলে এটিকে decision JSON-সহ একটি 2xx response ফেরত দিতে হয়। শুধু status code দিয়ে block হয় না।
  • mcp_tool: একটি MCP server-এর একটি tool call করে।
  • prompt: একবারের হ্যাঁ/না সিদ্ধান্তের জন্য input একটি Claude model-এ পাঠায়।
  • agent: tool-সহ একটি subagent চালু করে। Agent hook এখনো experimental।

সব event পাঁচটি type-ই support করে না। যেমন, SessionStart শুধু command এবং mcp_tool support করে। Source 1সোর্স 1 Default timeout হলো command, http এবং mcp_tool-এর জন্য 600 s, prompt-এর জন্য 30 s, আর agent-এর জন্য 60 s। কিছু event-এ default আরও কম। Source 1সোর্স 1 command, http বা mcp_tool type-এর একটি PreToolUse hook timeout হলে tool call block হয় না। Source 1সোর্স 1

QA examples

Block edits to .env and migrations

Example: save this script as .claude/hooks/protect-files.sh and run chmod +x on it. It is adapted from the protect-files example in the hooks guide, including its line that changes Windows backslashes to slashes. Source 3সোর্স 3 On Windows, tool_input.file_path has backslashes, and a check written with slashes never matches it. Source 1সোর্স 1 The .env pattern also matches names such as .envrc.

#!/bin/bash
# Example: block edits to .env files, migrations, and .git/
FILE_PATH=$(jq -r '.tool_input.file_path // empty')
# Change Windows backslashes to slashes so the patterns also match on Windows
FILE_PATH="${FILE_PATH//\\//}"

for pattern in ".env" "/migrations/" ".git/"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches the protected pattern $pattern" >&2
    exit 2
  fi
done
exit 0

Register it in .claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"
          }
        ]
      }
    ]
  }
}

Test it before you trust it. Source 3সোর্স 3

echo '{"tool_name":"Write","tool_input":{"file_path":"/repo/db/migrations/001.sql"}}' | .claude/hooks/protect-files.sh
echo $?   # 2, and the "Blocked" message on stderr

Also add deny rules

This hook sees only the Edit and Write tools. A Bash command can also change a file. Read and Edit deny rules cover:

  • Claude's file tools.
  • The file commands that Claude Code recognizes in Bash (such as cat, sed, and tee).
  • Redirections.

These rules do not cover any script. For blocking at the operating system level, use the sandbox. Source 5সোর্স 5 Add rules such as Read(./.env) and Edit(./.env) to permissions.deny.

Format after edits

This example is adapted from the hooks guide, which runs Prettier on every file that Claude edits or writes: Source 3সোর্স 3

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
          }
        ]
      }
    ]
  }
}

সহজ English

The first example hook blocks edits to .env files, migrations, and .git/. It is a PreToolUse script for Edit|Write. It reads the file path from stdin and exits with code 2 if the path matches a protected pattern. It changes Windows backslashes to slashes, so the check also matches on Windows. Source 3সোর্স 3 Source 1সোর্স 1 Test it before you trust it. Source 3সোর্স 3 This hook does not see Bash commands. Read and Edit deny rules also cover the file commands that Claude Code recognizes in Bash, but they do not cover any script. Source 5সোর্স 5 Add rules such as Read(./.env) and Edit(./.env) to permissions.deny.

The second hook runs Prettier on every file that Claude edits or writes. Source 3সোর্স 3

বাংলা ব্যাখ্যা

এই section-এ QA কাজের জন্য চারটি উদাহরণ hook আছে।

প্রথম hook .env file, migrations এবং .git/-এ edit block করে। এটি Edit|Write-এর জন্য একটি PreToolUse script। এটি stdin থেকে file path পড়ে, আর path কোনো protected pattern-এর সাথে মিললে exit code 2 দেয়। এটি Windows-এর backslash-গুলোকে slash-এ বদলায়, তাই check-টি Windows-এও মেলে। Source 3সোর্স 3 Source 1সোর্স 1 বিশ্বাস করার আগে এটি test করুন। Source 3সোর্স 3 এই hook Bash command দেখে না। Read এবং Edit deny rule Claude Code-এর চেনা Bash file command-গুলোও cover করে, কিন্তু কোনো script cover করে না। Source 5সোর্স 5 তাই permissions.deny-তে Read(./.env) এবং Edit(./.env)-এর মতো rule যোগ করুন।

দ্বিতীয় hook Claude যে file edit বা write করে, তার প্রতিটিতে Prettier চালায়। Source 3সোর্স 3

Run tests after edits

"async": true runs a command hook in the background. An async hook cannot block. Its output reaches Claude on the next turn through additionalContext or systemMessage. Source 1সোর্স 1

Example: .claude/hooks/run-tests-async.sh runs the tests after Claude edits a test file and reports the result to Claude.

#!/bin/bash
# Example: run the tests after Claude edits a test file
FILE_PATH=$(jq -r '.tool_input.file_path // empty')

case "$FILE_PATH" in
  *.spec.ts|*.test.ts) ;;
  *) exit 0 ;;
esac

if npm test --silent > /dev/null 2>&1; then
  RESULT="Tests passed after the edit of $FILE_PATH"
else
  RESULT="Tests failed after the edit of $FILE_PATH. Run npm test to see the failures."
fi
jq -n --arg ctx "$RESULT" '{hookSpecificOutput: {hookEventName: "PostToolUse", additionalContext: $ctx}}'
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh",
            "async": true
          }
        ]
      }
    ]
  }
}

A PostToolUse hook on Edit|Write does not run when a Bash command or a process outside Claude Code rewrites the file. Use FileChanged for that case. Source 1সোর্স 1

Log shell commands

Example

This audit-log hook is a tutorial example, not a docs example. It uses the session_id and tool_input.command fields of the Bash input. Source 1সোর্স 1 It was tested on Linux with jq. It is not tested on Windows.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '[(now|todate), .session_id, .tool_input.command] | @tsv' >> \"$CLAUDE_PROJECT_DIR\"/.claude/bash-audit.log"
          }
        ]
      }
    ]
  }
}

Each line has the time, the session ID, and the command. Commands can contain secrets, so keep bash-audit.log out of git.

সহজ English

The third hook runs the tests in the background ("async": true) after Claude edits a test file. An async hook cannot block. Its output reaches Claude on the next turn. Source 1সোর্স 1 It does not run when a Bash command or another process rewrites the file. Use FileChanged for that case. Source 1সোর্স 1

The fourth hook is a tutorial example. It writes each shell command to bash-audit.log, with the time and the session ID. Commands can contain secrets, so keep this file out of git.

বাংলা ব্যাখ্যা

তৃতীয় hook Claude একটি test file edit করার পরে background-এ ("async": true) test চালায়। Async hook block করতে পারে না। এর output Claude পরের turn-এ পায়। Source 1সোর্স 1 কোনো Bash command বা Claude Code-এর বাইরের কোনো process file আবার লিখলে এটি চলে না। সেজন্য FileChanged ব্যবহার করুন। Source 1সোর্স 1

চতুর্থ hook এই tutorial-এর নিজের উদাহরণ। এটি প্রতিটি shell command সময় আর session ID-সহ bash-audit.log-এ লেখে। Command-এ secret থাকতে পারে, তাই এই file git-এর বাইরে রাখুন।

Debug and stay safe

When a hook does not fire

  1. Run /hooks. It opens a read-only browser of your hooks and shows where each one comes from. Source 1সোর্স 1 Check that the hook is under the correct event. Source 3সোর্স 3
  2. Check the matcher. Matchers are case-sensitive. Source 3সোর্স 3
  3. Pipe sample JSON into the script and check the exit code with echo $?. Source 3সোর্স 3
  4. Start Claude Code with claude --debug-file /tmp/claude.log, or run /debug during a session. Source 3সোর্স 3

A Stop hook that blocks eight times in a row is overridden. Check the stop_hook_active input field and exit 0 early. Source 3সোর্স 3

Trust and CI

Hooks run with your permissions

Command hooks run shell commands with your full user permissions. Source 1সোর্স 1 In an interactive session, hooks from settings files run only after you accept the workspace trust dialog. In a -p or SDK session, Claude Code treats the folder as trusted, so committed hooks run. Source 1সোর্স 1 Review .claude/settings.json in a repository that you did not write before you run Claude Code on it in CI.

The docs give these security practices for hook scripts: validate input, quote shell variables, block .. in paths, use absolute paths, and skip sensitive files such as .env, .git/, and keys. Source 1সোর্স 1

  • "disableAllHooks": true in settings turns hooks off. It cannot turn off managed hooks from user or project settings. Source 1সোর্স 1
  • On Windows without Git Bash, hooks run in PowerShell by default. Use the matcher Bash|PowerShell and "shell": "powershell". Source 1সোর্স 1

See it in practice

The case study has a PreToolUse hook that adds context before a skill runs, in Bug Hunting with a Review Gate. What to Fix in the Setup shows hook mistakes and their fixes.

সহজ English

A hook is a small script that Claude Code runs at set moments. If a hook does not run, try these steps:

  1. Run /hooks. It shows your hooks and where each one comes from. Source 1সোর্স 1 Check that the hook is under the right event. An event is the moment that starts the hook. Source 3সোর্স 3
  2. Check the matcher. The matcher is the rule that picks which tool calls the hook applies to. Upper and lower case letters count as different. Source 3সোর্স 3
  3. Send sample JSON into the script. JSON is the text format the hook receives as input. Source 3সোর্স 3
  4. Check the exit code with echo $?. The exit code is the number the script gives back when it ends. Source 3সোর্স 3
  5. Start Claude Code with claude --debug-file /tmp/claude.log. You can also run /debug during a session. Source 3সোর্স 3

A Stop hook can block Claude from stopping. If it blocks eight times in a row, Claude Code overrides it. Check the stop_hook_active field and exit 0 early. Exit 0 means the script ends and signals success. Source 3সোর্স 3

Hooks run with your permissions. Command hooks run shell commands. They have all of your user permissions. Source 1সোর্স 1

A -p or SDK session is a run without a person at the keyboard. In that kind of run, Claude Code treats the folder as trusted. So hooks saved in the repository run. Source 1সোর্স 1

Take care with a repository you did not write. Before you run Claude Code on it in CI, read its .claude/settings.json.

"disableAllHooks": true in settings turns hooks off. It cannot turn off managed hooks from user or project settings. Source 1সোর্স 1

On Windows without Git Bash, hooks run in PowerShell by default. Use the matcher Bash|PowerShell and "shell": "powershell". Source 1সোর্স 1

বাংলা ব্যাখ্যা

Hook না চললে এই ধাপগুলো করুন:

  1. /hooks চালান। এটি আপনার hook-গুলো দেখায়, আর প্রতিটি কোথা থেকে এসেছে তা-ও দেখায়। Source 1সোর্স 1 Hook-টি সঠিক event-এর নিচে আছে কিনা দেখুন। Source 3সোর্স 3
  2. Matcher দেখুন। Matcher case-sensitive। Source 3সোর্স 3
  3. Sample JSON script-এ pipe করুন এবং echo $? দিয়ে exit code দেখুন। Source 3সোর্স 3
  4. claude --debug-file /tmp/claude.log দিয়ে Claude Code চালু করুন, অথবা session চলার সময় /debug চালান। Source 3সোর্স 3

যে Stop hook পরপর আটবার block করে, সেটি override হয়ে যায়। stop_hook_active field দেখুন এবং আগেভাগেই exit 0 দিন। Source 3সোর্স 3

Command hook আপনার পূর্ণ user permission নিয়ে shell command চালায়। Source 1সোর্স 1 -p বা SDK session-এ Claude Code folder-টিকে trusted ধরে, তাই commit করা hook চলে। Source 1সোর্স 1 যে repository আপনি লেখেননি, CI-তে তার ওপর Claude Code চালানোর আগে তার .claude/settings.json review করুন।

Settings-এ "disableAllHooks": true hook বন্ধ করে। User বা project settings থেকে এটি managed hook বন্ধ করতে পারে না। Source 1সোর্স 1 Git Bash ছাড়া Windows-এ matcher Bash|PowerShell এবং "shell": "powershell" ব্যবহার করুন। Source 1সোর্স 1

Reference

All 34 events

SessionStart, Setup, InstructionsLoaded, UserPromptSubmit, UserPromptExpansion, PreSkillShellCommand, MessageDisplay, PreToolUse, PermissionRequest, PostToolUse, PostToolUseFailure, PostToolBatch, PermissionDenied, Notification, SubagentStart, SubagentStop, TaskCreated, TaskCompleted, Stop, StopFailure, TeammateIdle, ConfigChange, CwdChanged, DirectoryAdded, FileChanged, WorktreeCreate, WorktreeRemove, PreCompact, PostCompact, PreModelSwitch, PostModelSwitch, Elicitation, ElicitationResult, SessionEnd. Source 1সোর্স 1

More options

  • if filters a tool event with permission-rule syntax, for example "Bash(git *)" or "Edit(*.ts)". One rule per if. On other events, a hook with if never runs. Source 1সোর্স 1 "Edit(src/**)" matches only src in the working directory. Use "Edit(**/src/**)" for any depth. Source 1সোর্স 1
  • Exec form: command plus an args list, for example "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/check-style.sh", "args": []. It needs no shell quotes. Source 1সোর্স 1
  • asyncRewake runs the hook in the background and wakes Claude on exit code 2. Source 1সোর্স 1
  • PostToolUse can replace the tool output with updatedToolOutput. Source 1সোর্স 1
  • For an MCP tool, the PreToolUse input also has mcp_server with name and source (v2.1.274 or later). Base trust decisions on source, not on name. Source 1সোর্স 1
  • PreToolUse top-level decision and reason are deprecated. Other events, such as PostToolUse and Stop, use a top-level decision: "block" with a reason. Source 1সোর্স 1
  • Hooks in subagent frontmatter run only while the subagent runs. Hooks in skill frontmatter run for the rest of the session after the skill is used. once: true works only in skill frontmatter. Source 1সোর্স 1
  • SessionEnd hooks share a time budget of 1.5 s. If your settings set a longer per-hook timeout, Claude Code raises the budget to match, up to 60 s. Source 1সোর্স 1

সহজ English

The hooks reference lists 34 events in all. Source 1সোর্স 1 Some more options:

বাংলা ব্যাখ্যা

Hooks reference-এ মোট 34টি event আছে। Source 1সোর্স 1 আরও কিছু option:

  • if permission-rule syntax দিয়ে একটি tool event filter করে, যেমন "Bash(git *)"। Source 1সোর্স 1
  • asyncRewake hook-টি background-এ চালায় এবং exit code 2-এ Claude-কে জাগিয়ে তোলে। Source 1সোর্স 1
  • PostToolUse updatedToolOutput দিয়ে tool-এর output বদলে দিতে পারে। Source 1সোর্স 1
  • once: true শুধু skill frontmatter-এ কাজ করে। Source 1সোর্স 1
  • SessionEnd hook-গুলো 1.5 s-এর একটি time budget ভাগ করে নেয়। আপনার settings-এ per-hook timeout বেশি হলে budget-ও সেই অনুযায়ী বাড়ে, সর্বোচ্চ 60 s পর্যন্ত। Source 1সোর্স 1
  1. [1]
    Hooks reference

    Anthropic (Claude Code docs) · accessed 2026-10-10দেখা হয়েছে: 2026-10-10

  2. [2]
    Extend Claude with skills

    Anthropic (Claude Code docs) · accessed 2026-10-10দেখা হয়েছে: 2026-10-10

  3. [3]
    Automate actions with hooks (guide)

    Anthropic (Claude Code docs) · accessed 2026-10-10দেখা হয়েছে: 2026-10-10

  4. [4]
    Environment variables

    Anthropic (Claude Code docs) · accessed 2026-10-10দেখা হয়েছে: 2026-10-10

  5. [5]
    Configure permissions

    Anthropic (Claude Code docs) · accessed 2026-10-10দেখা হয়েছে: 2026-10-10