skip to content

When you write a Claude Code PreToolUse script that guards protected files, what makes the script itself safe and reliable?

level: middleimportance: should knowfreq 14%

answer

  1. a gate that silently is not there
  2. script path anchored to the project root
  3. quote every variable, parse with jq
  4. chmod +x, then pipe in sample JSON
  5. the shell can still reach the file

basics

~20 s

Reference the guard script as "$CLAUDE_PROJECT_DIR"/.claude/hooks/... or in exec form, make it executable, parse stdin with jq, quote variables, check the path, and block with exit 2 plus a stderr reason. Test it: a wrong path leaves the gate open.

solid answer

~40 s

I register a `PreToolUse` hook on `Edit|Write` whose command is `"$CLAUDE_PROJECT_DIR"/.claude/hooks/protect-files.sh`, or the same path in exec form with `"args": []` so no shell quoting is involved. `$CLAUDE_PROJECT_DIR` anchors the script to the project root whatever directory Claude has moved into. The script is `chmod +x`, reads stdin once, extracts `tool_input.file_path` with `jq -r '... // empty'`, quotes every variable, normalises Windows backslashes and rejects `..`, then exits 2 with a reason on stderr, which Claude receives as feedback. I test it by piping sample JSON in and checking `$?`, and I watch the first real run: a mistyped or non-executable path produces only a non-blocking error notice and the edit goes ahead. Finally, the guard covers the file tools only; a `permissions.deny` rule is what keeps Claude's tools away from `.env`.

code

bash · 18 lines
bash
#!/bin/bash
# .claude/hooks/protect-files.sh: PreToolUse guard for Edit|Write
command -v jq >/dev/null || { echo "Blocked: jq missing, cannot check the path" >&2; exit 2; }
input=$(cat)
file_path=$(jq -r '.tool_input.file_path // empty' <<<"$input")
[ -z "$file_path" ] && exit 0
file_path="${file_path//\\//}"          # Windows separators to /
if [[ "$file_path" == *".."* ]]; then
  echo "Blocked: path traversal in $file_path" >&2
  exit 2
fi
for pattern in ".env" "package-lock.json" ".git/"; do
  if [[ "$file_path" == *"$pattern"* ]]; then
    echo "Blocked: $file_path matches protected pattern '$pattern'" >&2
    exit 2
  fi
done
exit 0

go deeper

for a junior

Recall the shape: a PreToolUse hook on Edit|Write runs a script that reads the file path from stdin and exits 2 with a stderr message to block.

for a middle

Explain why the path uses $CLAUDE_PROJECT_DIR, the difference between shell form and exec form, chmod +x, quoting, and how to test the script by piping sample JSON into it.

for a senior

Show the failure modes that silently open the gate: a typo in the path, a missing jq, exit 1 instead of 2. Make the script fail closed and say which layer is the real boundary for secrets.

for a principal

Treat guard scripts as shared code with full user privileges: review, test and version them, and decide which rules stay in hooks and which belong in permission rules or the sandbox.

## What the guard does A **protected-file guard** is a `PreToolUse` command hook that runs before Claude's `Edit` or `Write` tool touches a file. If the target matches a protected pattern (`.env`, a lock file, anything under `.git/`) the script exits with code **2** and writes a reason to stderr; Claude Code cancels the tool call and passes the reason to Claude so it can change approach. Any other outcome lets the normal permission flow continue. The interesting part is not the idea but the script: a guard that fails quietly is worse than none, because the team believes it is there. ## Registering it so the path always resolves Claude can `cd` during a session, and hooks run in the current directory. A relative path such as `.claude/hooks/protect-files.sh` can therefore stop resolving. Claude Code provides **`$CLAUDE_PROJECT_DIR`**, the project root where the session started, and exports it to the hook process. | Form | How you write it | What to watch | |---|---|---| | **Shell form** (no `args`) | `"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"` | wrap the placeholder in double quotes so a path with spaces survives; the shell may source a profile | | **Exec form** (`args` present) | `"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-files.sh", "args": []` | no shell at all, so no quoting and no tokenising; the placeholder is substituted as a plain string | If Claude enters a worktree, `$CLAUDE_PROJECT_DIR` stays at the original root (so the script is still found) while the `cwd` field in the hook's input follows Claude. ## Writing the script defensively - **Make it executable** with `chmod +x` on macOS and Linux; a non-executable script cannot start. - **Read stdin once** (`input=$(cat)`) and parse it with `jq`; use `// empty` so a missing field yields an empty string rather than the text `null`. - **Quote every variable** (`"$file_path"`, not `$file_path`). Paths can contain spaces and shell metacharacters. - **Normalise and validate the path.** File-tool paths arrive absolute with the platform's separators, so convert backslashes before matching, and reject `..` segments. - **Fail closed on your own errors.** If `jq` is missing, `$(jq ...)` returns nothing and a naive script exits 0, which allows everything. Check for the dependency and exit 2 with a reason instead. - **Send messages to stderr** on a block; stdout is reserved for JSON output. - **Skip sensitive files in your own logic too**: a guard that logs full file contents can leak the secret it protects. ## Failure modes that leave the gate open 1. **Wrong path or missing execute bit.** The shell exits with a code like 127. Claude Code shows `Failed with non-blocking status code:` plus the interpreter's message, and the edit proceeds. Watch for that notice on the first run. 2. **Ordinary failure codes.** Only exit 2 blocks through the code alone; a script that exits 1 on a match lets the edit through (the full exit-code contract is its own subject). 3. **Profile noise.** In shell form, a profile that `echo`es on startup can corrupt JSON output; exit-2 guards are unaffected, JSON-emitting ones are not. 4. **Untested logic.** Test before trusting it: ```bash echo '{"tool_name":"Edit","tool_input":{"file_path":"/repo/.env"}}' | .claude/hooks/protect-files.sh; echo $? ``` ## Sharing the guard with a team - **Commit both halves.** The script under `.claude/hooks/` and the registration in `.claude/settings.json` travel together, and the execute bit has to be committed too. - **Windows.** A shell-form hook runs in Git Bash, or in PowerShell when Git Bash is missing. In a PowerShell command write `${CLAUDE_PROJECT_DIR}` or `$env:CLAUDE_PROJECT_DIR`; the bare `$CLAUDE_PROJECT_DIR` spelling resolves to nothing there. - **Review it like code.** A guard is a script every teammate's machine will execute; changes to it deserve the same review as production code. ## Where the guard stops The guard sees only the tools it matches. Claude can still change `.env` with a shell command unless something else stops it, and a substring check like `*".env"*` also blocks `.env.example`. The harder boundary is a `permissions.deny` rule, with the sandbox for shell commands; the hook adds a precise, explainable message on top. And because command hooks run **with your full user permissions, outside the sandbox**, the script is code you review like any other.

  • Why prefer exec form, with an args array, for a script referenced through ${CLAUDE_PROJECT_DIR}?
    In exec form Claude Code spawns the executable directly with `args` as the argument vector, so no shell tokenises the path: spaces, apostrophes and `$` pass through verbatim and the placeholder is substituted as a plain string. Shell form needs the placeholder wrapped in double quotes and runs through `sh -c` (or Git Bash or PowerShell on Windows), with that shell's quoting rules.
  • What does ${CLAUDE_PROJECT_DIR} point at after Claude enters a git worktree?
    It stays at the project root where the session started, so a hook command such as `${CLAUDE_PROJECT_DIR}/.claude/hooks/check-style.sh` still runs the script from the main checkout. The `cwd` field in the hook's input JSON follows Claude into the worktree, so read `cwd` when the script needs to know where Claude is working.
  • Is this guard enough to keep Claude away from .env?
    No. It sees only the `Edit` and `Write` tools, so a `Bash` command can still write the file. A `permissions.deny` rule for the file tools, plus the sandbox for shell commands, form the harder boundary; the hook adds a precise message and can cover cases rules cannot express.

  • A relative script path like .claude/hooks/guard.sh always resolves from the project root.
  • If the guard script is missing, Claude Code refuses the edit to stay on the safe side.
  • Unquoted $FILE_PATH is fine, because Claude's tool paths never contain spaces.
  • Hook scripts run sandboxed, with only the access Claude's own tools have.
  • A PreToolUse guard on Edit|Write stops every process from changing .env.