Omniscio

OmniscioGuidesA lint-before-commit hook

A Claude Code hook that lints before every commit

Ask Claude to run the linter and it usually will — until the turn where it does not, and the commit lands with the error still in it. A hook is the version that cannot be forgotten, and the moment to run it is before the commit rather than after.

Checked against Anthropic’s Claude Code hooks documentation on November 25, 2026. By the Omniscio team. Updated .

The hook, complete

Save this to .claude/hooks/lint-before-commit.sh, run chmod +x on it, and add the block to .claude/settings.json — merging it into an existing "hooks" object rather than replacing the file. The example uses ESLint, which needs to be installed and configured: the section below on swapping linters says what else changes. The block’s "onFailure": "block" needs Claude Code v2.1.295 or later; on an older build it is ignored and a broken hook lets the commit through.

#!/bin/bash
set -u
command -v jq >/dev/null 2>&1 || { echo "lint hook: jq is not installed." >&2; exit 2; }
input=$(cat)
dir=$(jq -r '.cwd // empty' <<<"$input")
[ -n "$dir" ] || dir="${CLAUDE_PROJECT_DIR:-$PWD}"
cd "$dir" 2>/dev/null || exit 0
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || exit 0

base=HEAD
git rev-parse --verify HEAD >/dev/null 2>&1 || base=$(git hash-object -t tree /dev/null)

files=()
while IFS= read -r -d '' f; do
  case "$f" in
    *.js|*.jsx|*.ts|*.tsx) files+=("$f") ;;
  esac
done < <( { git diff -z --name-only --diff-filter=ACMR "$base" 2>/dev/null
            git ls-files -z --others --exclude-standard 2>/dev/null; } )
[ "${#files[@]}" -eq 0 ] && exit 0

eslint="$PWD/node_modules/.bin/eslint"
if [ ! -x "$eslint" ]; then
  echo "Commit blocked: ESLint is not installed in this project." >&2
  exit 2
fi
if ! out=$("$eslint" --max-warnings=0 -- "${files[@]}" 2>&1); then
  printf 'Commit blocked: lint failed. Fix these before committing.\n%s\n' "$out" >&2
  exit 2
fi
exit 0
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "if": "Bash(git commit *)",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/lint-before-commit.sh",
            "timeout": 120,
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}

This script is Bash, so on Windows it needs Git Bash. Where Claude uses PowerShell instead, a Bash-only hook never fires. Do not answer that with a PowerShell block that calls the same .sh — PowerShell cannot run it, and with onFailure: "block" that would refuse every commit. Write an equivalent .ps1 and point a second block at it, or leave the hook off on that machine.

The problem it solves

An unused import, a shadowed variable, a promise nobody awaited: found by CI they cost a round trip, and found before the commit they cost one fix.

The reason to put it in a hook rather than in an instruction is that a lint rule is a policy, and a policy that depends on the model remembering is not a policy. The hook runs the same command every time, and Claude gets the errors as the reason its commit was refused, which is exactly the input it needs to fix them.

What each line does

PartJob
"PreToolUse"The event: it runs after Claude builds the tool’s parameters and before the tool call is processed, so the hook can refuse the commit before the command starts.
"matcher": "Bash"Limits the block to the Bash tool. On PreToolUse this matcher also covers shell commands Claude starts with the Monitor tool, where a hook’s allow and updatedInput have no effect.
"if": "Bash(git commit *)"Permission-rule syntax that filters on the command. Only evaluated on tool events.
the cwd readRuns the git commands where Claude is working. The settings block still uses $CLAUDE_PROJECT_DIR, but only to find this script: that variable stays at the project root where the session started, so committing from it would lint the wrong checkout in a worktree.
base=HEAD and the empty treeDiffs against HEAD, and against the empty tree when the repository has no commit yet, so the first commit is linted too.
git diff -z --name-only --diff-filter=ACMRLists tracked files that differ from the base, staged or not, NUL-separated so a path with a space stays one name, and drops deletions, which have nothing to lint.
git ls-files -z --othersAdds the untracked files, which a diff against HEAD never shows. Without this a brand-new file is never linted.
the while read -d '' loopFilters by extension and builds the argument list with no mapfile call, so the script does not depend on a bash 4 builtin.
$PWD/node_modules/.bin/eslintCalls the linter installed in the project and exits 2 with a message when there is none, instead of letting npx reach the network.
--max-warnings=0Treats a warning as a failure, so the gate matches what CI would report.
exit 2Blocks the tool call. The stderr above it becomes the reason Claude is shown, which is why the message says what to do.
timeout: 120Seconds. A command hook defaults to ten minutes, which is longer than anyone wants to wait on a lint.
onFailure: "block"Makes a hook that fails to start or hits its timeout block the commit instead of letting it through unlinted. Requires Claude Code v2.1.295 or later.

What the if pattern actually matches

It is not a substring search. Each subcommand of a Bash command is checked against the pattern separately, and leading VAR=value assignments are stripped first. That covers the shapes people actually write.

PatternCommandHook runs?
Bash(git commit *)git add -A && git commit -m "x"Yes, because each subcommand is checked
Bash(git commit *)npm test && git commit -m "x"Yes
Bash(git commit *)git statusNo, no subcommand matches
Bash(git push *)echo $(date)Yes — a pattern that specifies more than the command name runs the hook anyway on $(), backticks or $VAR

That last row is the quick answer’s hedge. Anthropic states the limit plainly: because the if filter is best-effort, use the permission system rather than a hook to enforce a hard allow or deny. A lint gate is a good fit for if because a miss is a missed lint rather than a security hole — but note what a false positive costs: the hook runs the linter anyway, so a command that was never a commit can still be refused while the tree has a lint error. If that bites, narrow the pattern.

Swapping the linter

The handler runs whatever command you give it, but four things in the script are ESLint-shaped and change with it.

  • The extension list. The case in the loop decides which files reach the linter. Ruff wants *.py; gofmt wants *.go. Leave the list as it is and the linter receives only JavaScript paths.
  • The flags. --max-warnings=0 is ESLint’s. Ruff’s equivalent is ruff check, which already exits non-zero on a finding.
  • The binary path. $PWD/node_modules/.bin/eslint and the [ ! -x ] check around it. Ruff lives wherever pip or uv put it, so both lines change.
  • Whether a finding is an exit code at all. gofmt -l lists the files that need formatting and exits 0, so as a gate it never blocks. Wrap it in a test on empty output, or use a linter that fails.

How to test that it fires

  1. Run the script by hand, from the repo root, with one lint error in the tree. It reads only the cwd field, so that is the only part of the event that matters:
    printf 'const unused = 1;\n' >> app.js
    echo '{"cwd":"'"$PWD"'"}' | .claude/hooks/lint-before-commit.sh; echo $?
    With an ESLint config that rejects unused variables you should see the lint output and exit 2. Remove the line and run it again: exit 0 and no output.
  2. Check the hook is registered. Type /hooks: a read-only browser that lists each hook under its event and says where it comes from.
  3. Ask Claude to commit. With a lint error in the working tree, ask for a commit. The call is refused, Claude sees your message and the lint output, and it should fix the file and try again — that second attempt is the proof the stderr reached it.
  4. Read the debug log when it does not. Start with claude --debug-file /tmp/claude.log, or run /debug mid-session. A hook that never ran and a hook that ran and exited 0 look identical in the conversation.

What makes this hook fail

1. It exits 1 instead of 2

The single most common version of this hook runs the linter and lets its exit code through. On PreToolUse, 1 is a non-blocking error: the commit goes ahead and you get a PreToolUse:Bash hook error notice nobody reads. The script has to exit 2 itself, which is why the linter’s status is captured and translated.

2. The file list is empty

A hook that reads git diff --cached sees nothing for git commit -a, because nothing is staged at PreToolUse time; one that reads git diff HEAD misses a file the same command just created. Either way the list is empty, the script exits 0, and the commit passes unlinted. The script above diffs against HEAD and adds git ls-files --others for exactly that reason.

3. The hook itself fails, and the commit goes through

Without onFailure, a script that cannot start or a lint that runs past its timeout is a non-blocking error: Claude Code carries out the action anyway. For a policy check that is the wrong default, which is why the block sets "onFailure": "block". The cost is the mirror image — a broken hook now blocks every commit — so test it by hand before you switch it on.

4. The linter is left to npx

npx --no-install still consults the registry when the package is missing; measured on npm 10.9.9 it fetched the ESLint manifest before failing. On a slow or blocked network that is a hang inside a hook rather than a fast error. Calling node_modules/.bin/eslint directly removes the question: either the project has the linter or the hook says so and exits 2.

5. Claude commits through PowerShell

On Windows, Claude treats PowerShell as the primary shell wherever it is enabled, and without Git Bash it does not register the Bash tool at all. A hook that matches only Bash never fires, and every commit sails past it. Match Bash|PowerShell, or add a second block.

6. It lints the wrong checkout

A script that runs at $CLAUDE_PROJECT_DIR lints the main checkout even when Claude is working in a worktree, so it sees an empty or unrelated change set and exits 0. Read the cwd field from the event instead, as the script here does.

Where Omniscio fits

A lint gate belongs in the project. Commit .claude/settings.json and every teammate and every agent working in that repository meets the same rule. Omniscio takes the other angle: its Hooks panel composes the hooks it ships, and any you define, into every session it spawns, keeping them in its own database rather than writing into your global Claude configuration, with a global switch and per-project overrides.

The hooks examples hub collects the other recipes, the Claude Code hooks guide covers every event, and the hooks builder assembles a block like this one. Omniscio runs on Windows, macOS and Linux, and the pricing page covers the plans.

How this page was written

Everything about events, the if field and its Bash matching rules, matcher values, input fields, exit codes, onFailure, timeouts and where cwd points in a worktree was read from Anthropic’s Claude Code hooks reference on November 25, 2026, quoted from the page as it reads today.

The script was run on this machine in throwaway repositories with a stub linter on the path, covering a clean tree, a lint error, an untracked new file, a missing linter and a cwd that differs from the project root. No live Claude Code session was configured to run it, so the page describes the documented behaviour of the block and the measured behaviour of the script.

Sources

  • Anthropic’s Hooks reference, for PreToolUse, the if field and its Bash matching table, matchers, onFailure, exit codes and handler fields, read November 25, 2026.
  • Anthropic’s Automate actions with hooks, for the advice to test a hook by piping sample JSON into it, read November 25, 2026.

Common questions

How do I stop Claude committing code that fails lint?

A PreToolUse hook on Bash with an if pattern of Bash(git commit *) runs your linter before the command. Exit 2 blocks the call, and your stderr becomes the reason Claude is shown, so it can fix the errors and try again.

Why is it not blocking?

Check four things in order: the script exits 2 and not 1, the if pattern matches the command Claude actually ran, the linter is installed and configured in the project, and the file list is not empty. A missing linter is not silent — the script says so and exits 2 — but a linter with no config file reports an error that the script passes on as a failed lint.

Staged files or all changed files?

All changed files, including untracked ones, if you want it to work with git commit -a and with a commit that also creates a file. At PreToolUse time the commit has not run, so nothing is staged for that form. The script diffs against HEAD and adds the untracked files git reports.

What about the repository’s own pre-commit hook?

Use it when it exists. A git pre-commit hook runs for every commit, not only the ones Claude makes through Bash, and it is the stronger guarantee. The Claude Code hook is for the case where you want the check to apply to the agent without changing the team’s commit rules.

Can I use Ruff or gofmt instead of ESLint?

Yes, and three things change: the extension list in the loop, the flags (--max-warnings=0 is ESLint’s), and whether a finding is an exit code at all. gofmt -l exits 0 and only lists files, so wrapping it in a test on empty output is what makes it a gate.

The same gate in every session

Omniscio runs your Claude Code sessions side by side and composes the hooks it ships, and any you define, into every one it spawns, so a lint rule does not depend on which folder you opened.

The features page covers what else it does, pricing covers the plans, and you can download it for Windows, macOS or Linux.