Seongwoo Choi / Journal

Claude Code hooks, tested: five scripts you can copy

At a glanceFive small Claude Code hooks with a test script: protect files, block risky commands, format after edits, check before stopping, and log every command.

TestedAll five scripts were run on Linux with sample input; the results shown are the real exit codes. Not run inside a live session or on Windows.

You need
Claude Code, a project folder, bash and jq. On Windows, Git for Windows provides bash.
You end up with
Five working hooks in .claude/hooks, one settings file that registers them, and a script that proves each one behaves.
In this article 10 sections
  1. 1. How a hook works, in one picture
  2. 2. Protect files that must not change
  3. 3. Block commands that are hard to undo
  4. 4. Format a file after every edit
  5. 5. Do not finish while the check fails
  6. 6. Keep a record of every command
  7. 7. Register all five
  8. 8. Test them without Claude
  9. 9. When a hook is the wrong tool
  10. 10. When a hook does not fire

An instruction file asks. A hook enforces. When a rule in your project has no exceptions, such as never editing a generated folder, writing it in capital letters does not make it certain. A hook does, because Claude Code runs it every time, whatever the model decided. This guide gives you five small hooks and, more usefully, a way to test them without waiting for an agent to make the mistake.

1. How a hook works, in one picture

Claude wants to actedit a file, run a command, or finish
→
Your script runsit receives the details as JSON
→
Exit 0no objection, carry on
Exit 2blocked, and your message goes to Claude
The whole contract: JSON arrives on standard input, and the exit code is the answer.

Three facts cover most of what you need:

  • Input is JSON on standard input. For a file edit it includes tool_input.file_path. For a shell command it includes tool_input.command.
  • Exit code 2 blocks. Whatever the script printed to standard error is shown to Claude as the reason. The reference is explicit that exit code 1 does not block, even though 1 is the usual code for failure.
  • Exit code 0 is not approval. It only means the hook has no objection. The normal permission prompts still apply.
You need jqThe scripts use jq to read JSON. On macOS install it with brew install jq. On Windows the scripts run under Git Bash, which comes with Git for Windows; install jq with your package manager.

2. Protect files that must not change

Event: PreToolUse, for the Edit and Write tools. Save as .claude/hooks/protect-files.sh. It follows the example in Anthropic's guide, with one more pattern for a generated folder:

#!/bin/bash
# PreToolUse on Edit|Write: refuse changes to files that must not be touched.
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
FILE_PATH="${FILE_PATH//\\//}"   # Windows paths arrive with backslashes

PROTECTED=(".env" "package-lock.json" "/.git/" "/src/gen/")
for pattern in "${PROTECTED[@]}"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'. Ask the user before changing it." >&2
    exit 2
  fi
done
exit 0

The line that replaces backslashes matters on Windows. The reference says file paths arrive there with backslash separators, even when the script runs under Git Bash, and that a check written with forward slashes then never matches, so the edit goes through as if there were no hook.

The message is written for Claude, not for you. Tell it what to do next, here "ask the user", so it does not just try another route to the same file.

3. Block commands that are hard to undo

Event: PreToolUse, for the Bash tool. Save as .claude/hooks/block-commands.sh:

#!/bin/bash
# PreToolUse on Bash: stop a short list of commands that are hard to undo.
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

BLOCKED=("git push --force" "git push -f" "git reset --hard" "rm -rf /" "rm -rf ~" "drop table")
lowered=$(echo "$COMMAND" | tr '[:upper:]' '[:lower:]')
for pattern in "${BLOCKED[@]}"; do
  if [[ "$lowered" == *"$pattern"* ]]; then
    echo "Blocked: this command contains '$pattern'. Explain what you wanted to do and let the user run it." >&2
    exit 2
  fi
done
exit 0
A seat belt, not a wallMatching text catches honest mistakes. It does not stop a command that is spelled differently or hidden inside a script. For rules that must hold against anything, use permission deny rules and the sandbox, which Claude Code enforces itself.

4. Format a file after every edit

Event: PostToolUse, for Edit and Write. Save as .claude/hooks/format-on-edit.sh:

#!/bin/bash
# PostToolUse on Edit|Write: format the file that was just changed.
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
[ -f "$FILE_PATH" ] || exit 0

case "$FILE_PATH" in
  *.json)
    # jq rewrites the file with standard indentation, and fails on invalid JSON.
    if formatted=$(jq . "$FILE_PATH" 2>&1); then
      printf '%s\n' "$formatted" > "$FILE_PATH"
    else
      echo "$FILE_PATH is not valid JSON: $formatted" >&2
      exit 2
    fi
    ;;
  # Add your own formatters here, for example:
  # *.py) ruff format "$FILE_PATH" ;;
  # *.ts|*.tsx|*.js) npx prettier --write "$FILE_PATH" ;;
esac
exit 0

The JSON branch does two jobs. It tidies the file, and if the file is not valid JSON it exits with 2, so Claude is told at once and can repair it. The two commented lines show where your own formatters go; they were not run for this article.

A hook that succeeds is silent. Claude Code shows nothing in the conversation, so check the file itself the first time.

5. Do not finish while the check fails

Event: Stop, which fires when Claude tries to end its turn. Save as .claude/hooks/check-before-stop.sh:

#!/bin/bash
# Stop: the turn may not end while the project check fails.
INPUT=$(cat)
# If this hook already sent Claude back to work once, let it stop this time.
if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then
  exit 0
fi

CHECK="${PROJECT_CHECK:-npm test --silent}"   # replace with your project's check
if ! output=$($CHECK 2>&1); then
  echo "The check '$CHECK' failed. Fix it before finishing:" >&2
  echo "$output" | tail -n 20 >&2
  exit 2
fi
exit 0

The first if is the important part. Without it, a check that cannot pass would send Claude back to work again and again. The guide says Claude Code overrides a Stop hook after eight blocks in a row, and recommends exactly this test of stop_hook_active so your hook gives way first.

Keep the check fast. It runs every time Claude finishes a turn, so a type check or a small test group suits it better than a ten-minute suite.

6. Keep a record of every command

Event: PostToolUse, for Bash. Save as .claude/hooks/log-commands.sh:

#!/bin/bash
# PostToolUse on Bash: keep a plain record of every command that ran.
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
LOG="${CLAUDE_PROJECT_DIR:-.}/.claude/command-log.txt"
printf '%s\t%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$COMMAND" >> "$LOG"
exit 0

After a long unattended session, this file answers "what did it actually run?" in seconds. Add .claude/command-log.txt to .gitignore.

7. Register all five

Make the scripts executable, then put this in .claude/settings.json:

chmod +x .claude/hooks/*.sh
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" }
        ]
      },
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-commands.sh" }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-on-edit.sh" }
        ]
      },
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/log-commands.sh" }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-before-stop.sh" }
        ]
      }
    ]
  }
}

The matcher chooses which tools a hook applies to; Edit|Write means either. $CLAUDE_PROJECT_DIR is the project root, so the paths work wherever Claude Code is started from. Committing this file gives the whole team the same hooks. Inside a session, /hooks lists what is registered.

8. Test them without Claude

A hook you have not tested is a hope. Because the contract is only "JSON in, exit code out", you can test it from the shell. Save this as test-hooks.sh in the project root:

#!/bin/bash
# Run each hook the way Claude Code does: JSON on standard input, then read the exit code.
try() {   # try <expected exit code> <script> <json>
  message=$(echo "$3" | "$2" 2>&1 >/dev/null); code=$?
  [ "$code" = "$1" ] && verdict="ok  " || verdict="FAIL"
  printf '%s exit %s  %-22s %s\n' "$verdict" "$code" "$(basename "$2")" "${message:0:70}"
}
H=.claude/hooks
try 2 $H/protect-files.sh  '{"tool_name":"Edit","tool_input":{"file_path":"/home/me/app/.env"}}'
try 0 $H/protect-files.sh  '{"tool_name":"Edit","tool_input":{"file_path":"/home/me/app/src/index.ts"}}'
try 2 $H/protect-files.sh  '{"tool_name":"Write","tool_input":{"file_path":"C:\\project\\src\\gen\\client.ts"}}'
try 2 $H/block-commands.sh '{"tool_name":"Bash","tool_input":{"command":"git push --force origin main"}}'
try 2 $H/block-commands.sh '{"tool_name":"Bash","tool_input":{"command":"psql -c \"DROP TABLE users\""}}'
try 0 $H/block-commands.sh '{"tool_name":"Bash","tool_input":{"command":"npm test"}}'
PROJECT_CHECK=false try 2 $H/check-before-stop.sh '{"hook_event_name":"Stop","stop_hook_active":false}'
PROJECT_CHECK=true  try 0 $H/check-before-stop.sh '{"hook_event_name":"Stop","stop_hook_active":false}'
PROJECT_CHECK=false try 0 $H/check-before-stop.sh '{"hook_event_name":"Stop","stop_hook_active":true}'

Each line states the exit code it expects. This is the output from the run for this article:

$ ./test-hooks.sh
ok   exit 2  protect-files.sh       Blocked: /home/me/app/.env matches protected pattern '.env'. Ask the u
ok   exit 0  protect-files.sh
ok   exit 2  protect-files.sh       Blocked: C:/project/src/gen/client.ts matches protected pattern '/src/
ok   exit 2  block-commands.sh      Blocked: this command contains 'git push --force'. Explain what you wa
ok   exit 2  block-commands.sh      Blocked: this command contains 'drop table'. Explain what you wanted t
ok   exit 0  block-commands.sh
ok   exit 2  check-before-stop.sh   The check 'false' failed. Fix it before finishing:
ok   exit 0  check-before-stop.sh
ok   exit 0  check-before-stop.sh
Nine cases, nine as expected. The third line is the Windows path, blocked because the script normalizes the slashes.

The two remaining hooks change files, so they were checked by their effect:

HookTestResult
format-on-edit.shA JSON file written on two cramped linesExit 0; the file was rewritten with standard indentation
format-on-edit.shA JSON file cut off halfwayExit 2, with a message naming the file as invalid
log-commands.shTwo commands, npm test and git statusTwo lines in the log, each with a UTC timestamp

Run the test script whenever you change a hook, and add a line for each new rule. If a hook ever lets something through that it should have stopped, the first step is to add that case here and watch it fail.

9. When a hook is the wrong tool

You wantUse
A guideline with exceptionsA line in CLAUDE.md; let Claude judge
Something to happen every time, with no exceptionsA hook
Access that must be impossible, not just discouragedA permission deny rule or the sandbox
A check that holds even if someone skips the toolCI and branch protection

Anthropic's guide offers a test for both directions. If you keep adding emphasis to a line in CLAUDE.md and it is still missed, it belongs in a hook. If you have hooks for things that are only preferences, delete them.

10. When a hook does not fire

SymptomCheck
Nothing happensRun /hooks. If it is empty, the settings file is in the wrong place or is not valid JSON.
"Permission denied"The script is not executable; run chmod +x again.
The hook runs but does not blockIt exits with 1, not 2. Only 2 blocks.
Path checks never match on WindowsThe backslash line from step 2 is missing.
Claude keeps working and then warns about the Stop hookThe stop_hook_active test from step 5 is missing.
jq: command not foundInstall jq, and open a new terminal.

For how hooks sit beside the other project files, see Claude Code project setup. For plugins, which can bring hooks of their own, see plugins and MCP servers from the terminal.

Sources

This article reflects public information available when it was written. Versions, defaults and prices can change; check the linked official documentation.

All five scripts and the test script were run for this article on Linux with bash and jq 1.7, and the results table shows the actual exit codes and messages. They were tested the way the documentation describes, by sending sample input to each script, not inside a live Claude Code session. The Windows notes follow Anthropic's documentation as read on November 12, 2026 and were not run on Windows. Written for this site with AI assistance, from the sources above. For errors or additional information, please request a correction. Editorial policy