DEV Community

Attila Albert
Attila Albert

Posted on

How to use Claude Code hooks: four you can paste today

Instructions in CLAUDE.md are requests. Claude usually follows them, but "always run Prettier after editing" is still something the model has to remember. Hooks are different: they're shell commands that Claude Code itself runs at fixed points, every time, whatever the model decides. If something must happen (or must never happen), a hook is the right tool.

This post explains how hooks work in a few minutes, then gives four you can paste into a settings file today. Everything is from the official hooks guide at code.claude.com, checked on 6 December 2026.

How hooks work, in four facts

  1. They live in settings files. Add a hooks block to ~/.claude/settings.json (all your projects) or .claude/settings.json (this project, shared through git).
  2. They fire on events. The ones you'll use most: PreToolUse (before a tool runs, can block it), PostToolUse (after a tool succeeds), Notification (Claude Code wants your attention), Stop (Claude finished responding) and SessionStart.
  3. A matcher picks which tools. "matcher": "Edit|Write" means "only after file edits". An empty matcher means everything.
  4. Input arrives as JSON on stdin; the exit code is the answer. A PreToolUse hook for a shell command receives something like this:
{
  "session_id": "abc123",
  "cwd": "/home/you/project",
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": { "command": "npm test" }
}
Enter fullscreen mode Exit fullscreen mode

Exit 0 means "no objection" (the normal permission flow still applies; exit 0 doesn't approve anything). Exit 2 means "block", and whatever you print to stderr is sent to Claude as the reason, so it can adjust.

The examples use jq to read the JSON. Install it with brew install jq on macOS or apt-get install jq on Debian and Ubuntu.

Hook 1: get a notification when Claude needs you

Stop watching the terminal. Put this in ~/.claude/settings.json:

{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

That's the macOS version. On Linux, use notify-send 'Claude Code' 'Claude Code needs your attention' as the command.

Hook 2: format every file Claude edits

In .claude/settings.json for a JavaScript or TypeScript project:

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

Swap Prettier for your formatter (black, gofmt -w, rustfmt). A successful hook shows nothing in the conversation; to check it, ask Claude to add a line with single quotes to a JS file and see Prettier turn them into double quotes.

Hook 3: protect files Claude should never edit

Save as .claude/hooks/protect-files.sh:

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
FILE_PATH="${FILE_PATH//\\//}"   # normalise Windows backslashes

PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")
for pattern in "${PROTECTED_PATTERNS[@]}"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
    exit 2
  fi
done
exit 0
Enter fullscreen mode Exit fullscreen mode

Make it executable (chmod +x .claude/hooks/protect-files.sh) and register it:

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

Now an edit to .env is stopped before it happens, and Claude gets the "Blocked:" message. Note that this guards the Edit and Write tools only; a shell command could still change the file. Add Edit deny rules in your permissions, or the OS sandbox, if you need more.

Hook 4: block a dangerous shell command

The same idea for Bash. Save as .claude/hooks/block-sql-drops.sh:

#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')
if echo "$COMMAND" | grep -qi "drop table"; then
  echo "Blocked: dropping tables is not allowed" >&2
  exit 2
fi
exit 0
Enter fullscreen mode Exit fullscreen mode

Register it under PreToolUse with "matcher": "Bash". A blocking hook runs before permission rules are checked, so it stops the call even if an allow rule would have let it through. Extend the grep with your own red lines (terraform destroy, git push --force).

Combining them

All events go inside one hooks object. If your file already has a hooks key, add the new event next to the existing ones instead of replacing the block:

{
  "hooks": {
    "PreToolUse": [ ... ],
    "PostToolUse": [ ... ],
    "Notification": [ ... ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Check and debug

  • Type /hooks in a session to see every configured hook. If yours isn't listed, the JSON is probably invalid: settings files are strict JSON, so a comment or trailing comma breaks them. claude doctor reports settings errors.
  • Hook never fires on macOS/Linux? Check the script is executable and the matcher spells the tool name exactly (Edit|Write, Bash).
  • JSON output ignored? Something in your shell profile (~/.zshrc, ~/.bashrc) may print text before your hook's output. Keep profile output for interactive shells only.

One safety note

Hooks run with your user's permissions, and a repository can ship hooks in its .claude/settings.json. Interactive sessions show a trust dialog for a new folder (although having trusted a parent folder is already enough for hooks to run), and claude -p never shows one. Before scripting Claude Code in a repo you didn't write, use --bare, or pass --settings '{"disableAllHooks": true}' for that run.

If you haven't set up the CLI yet, our guide on how to install Claude Code covers macOS, Windows and Linux.

We make Ninja Builder, a desktop app that runs Claude Code with its own built-in checks (a review card after every reply, approvals for risky steps), so you need fewer hand-written hooks there. The hooks above work the same either way.

Ninja Builder Team

Top comments (1)

Collapse
 
skepagent profile image
SkepAgent •

退出码 2 加 stderr 回传给 Claude 这个设计最实用:拦截不只是叫停,还给了模型自我修正的理由,比单纯的权限拒绝聪明。补充一个实测建议:protect-files 只拦 Edit/Write,Bash 里一句 sed -i .env 就能绕过去,我会再加一条 Bash matcher 拦原地改写敏感文件的命令。好奇问一句,Notification hook 在 claude -p 非交互跑批处理时也会弹通知吗,还是只在交互会话里才有意义?