c/agents › command
0votes

Claude Code hooks: format on save and block dangerous commands

Template Tested
submitted by CommandVault editors to c/agents

A .claude/settings.json with hooks that auto-format edited files and stop risky shell commands.

Template · 2 variables
Add this to `.claude/settings.json` in your project (merge it with any settings you already have):

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "f=$(jq -r '.tool_input.file_path // empty'); [ -n \"$f\" ] && npx prettier --write \"$f\" || true" }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": ".claude/hooks/block-dangerous.sh" }
        ]
      }
    ]
  }
}
```

And create `.claude/hooks/block-dangerous.sh`, then run `chmod +x .claude/hooks/block-dangerous.sh`:

```bash
#!/usr/bin/env bash
# Stops risky shell commands before Claude Code runs them. Needs jq.
cmd=$(jq -r '.tool_input.command // empty')
block() { echo "Blocked by project hook ($1): $cmd" >&2; exit 2; }   # exit 2 = block and tell Claude why

# Recursive delete of the root, your home folder, or the whole current folder (any flag order).
if echo "$cmd" | grep -Eq '(^|[;&|[:space:]])rm[[:space:]]([^;&|]*[[:space:]])?(-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)([[:space:]]|$)' &&
   echo "$cmd" | grep -Eq '(^|[;&|[:space:]])rm[[:space:]][^;&|]*[[:space:]](/|/\*|~|~/|\$HOME|\$HOME/|\.|\./|\.\.|\*)([[:space:];&|]|$)'; then
  block "recursive delete of /, ~ or ."
fi

# Force pushes: -f, --force, --force-with-lease, or a +branch refspec.
if echo "$cmd" | grep -Eq 'git[[:space:]]+push([[:space:]]|$)' &&
   echo "$cmd" | grep -Eq '[[:space:]](-[a-zA-Z]*f[a-zA-Z]*|--force|--force-with-lease(=[^[:space:]]*)?|--force-if-includes)([[:space:]]|$)|[[:space:]]\+[^[:space:]]+'; then
  block "force push"
fi

# Destructive SQL.
if echo "$cmd" | grep -Eiq 'drop[[:space:]]+(table|database|schema)|truncate[[:space:]]+(table[[:space:]]+)?[a-z_"`]'; then
  block "destructive SQL"
fi

# Your own extra rule (an extended regex). Leave it empty to skip.
EXTRA='terraform destroy|kubectl delete namespace'
if [ -n "$EXTRA" ] && echo "$cmd" | grep -Eq "$EXTRA"; then
  block "project rule"
fi
exit 0
```

**Needs:** `jq` (`brew install jq` or `apt install jq`) and your formatter installed in the project (for example `npm i -D prettier`), not just available through npx.

**What it blocks:** recursive deletes of `/`, `~` or the whole current folder in any flag order (`rm -rf`, `rm -fr`, `rm -r -f`), force pushes (`-f`, `--force`, `--force-with-lease`, `+branch`), `DROP TABLE/DATABASE/SCHEMA` and `TRUNCATE`, plus your extra pattern. Normal cleanups like `rm -rf node_modules` or `rm -rf /tmp/cache` still run.

**Check it:** run `/hooks` to see both hooks loaded, ask Claude to edit a file and confirm it was formatted, then ask it to run `psql -c "DROP TABLE x"` and confirm it's blocked.
Formats one file passed at the end, e.g. npx prettier --write, ruff format or gofmt -w
An extended regex for anything else to block, e.g. terraform destroy|kubectl delete ns
0 commentsreport

Guide

What you get: After every Edit/Write Claude Code runs your formatter on the changed file, and Bash commands matching the blocked patterns are stopped before they run. Best for Teams using Claude Code who want automatic formatting and a basic guardrail against a few risky shell commands..

Before you start

  • Claude Code
  • jq installed (both hooks use it)
  • Your formatter available (we used npx prettier --write; prettier is not in create-next-app's dependencies and worked here only because it was already in the npx cache)
  • chmod +x .claude/hooks/block-dangerous.sh

Worked example (Oct 17, 2026, Claude Code 2.1.296)

Input

{{formatter_command}} = npx prettier --write, {{extra_blocked_pattern}} = git reset --hard. (a) Asked Claude to change only the title string in a deliberately badly formatted layout.tsx. (b) Asked Claude to run git push --force origin main in a repo with no remote.

Result

Claude Code: (a) "A hook reformatted the file after my edit" — diff shows the metadata block and RootLayout( { reformatted. (b) "PreToolUse:Bash hook error: [.claude/hooks/block-dangerous.sh]: Blocked by project hook: git push --force origin main"

Both hooks fired in claude -p. The format hook reformatted the whole file, not just the edited line. The block hook stopped the push even though Bash(git push:*) was allowed, so the hook (not the permission system) did the blocking. Direct checks of the script: blocked 'git push --force', 'git push --force-with-lease', 'git reset --hard', 'rm -rf /tmp/cache'; NOT blocked: 'git push -f origin main', 'git push origin +main', 'rm -fr /'. Codex: not applicable (Claude Code hooks). After this test the block script was rewritten: the old one missed git push -f, +branch pushes and rm -fr /, and blocked harmless paths like rm -rf /tmp/cache. The new script passes 22 sample commands and blocked DROP TABLE in a real Claude Code session; the formatter step now does nothing when there's no file, and the page lists the requirements (jq, formatter installed).

How to check it worked

  • Ask Claude to edit a messy file and check git diff shows formatting changes
  • Ask Claude to run a blocked but harmless command (e.g. git push --force in a repo with no remote) and look for 'Blocked by project hook'
  • Pipe sample JSON into the script, e.g. echo '{"tool_input":{"command":"git push -f"}}' | .claude/hooks/block-dangerous.sh; echo $?

Common problems

  • Short or alternate forms slip through: git push -f, git push origin +main, rm -fr / were not blocked
  • 'rm -rf /' also matches any absolute path, e.g. rm -rf /tmp/cache was blocked
  • The formatter rewrites the whole file, so a one-line edit can produce a larger diff
  • If jq or the formatter is missing, the hooks cannot work as intended

How to install these hooks

  1. Fill in the 2 blanks above; Copy puts your answers into the file.
  2. Merge the "hooks" section into .claude/settings.json (this project, can be committed) or ~/.claude/settings.json (all your projects). Don't replace your other settings.
  3. If it references a script, save the script where the path points and make it executable (chmod +x).
  4. Run /hooks in Claude Code to confirm they're loaded and see which file each comes from.
  5. Test a blocked case on purpose: a PreToolUse hook that exits with code 2 blocks the tool call and shows Claude the reason.
  6. Careful: this one is marked medium risk. Review what the AI suggests before you run it on real systems or data.
  • {{formatter_command}} Formats one file passed at the end, e.g. npx prettier --write, ruff format or gofmt -w
  • {{extra_blocked_pattern}} An extended regex for anything else to block, e.g. terraform destroy|kubectl delete ns

Checked against Claude Code docs: hooks.

More from c/agents

See all of c/agents →
0 comments

Log in to join the discussion.