Skip to content
Max Narditdata & ai systems
← Articles
3 mindev

Claude Code's PreSkillShellCommand hook: write it as an allow-list for the shell commands a skill runs as it loads

Write the new hook as an allow-list keyed to the skill. A skill argument can land inside a load-time shell command, a deny-list that looks for curl or $( misses the payload that simply closes the quote, and a code fence around the line does not stop it from running either.

Contents

Claude Code 2.1.332, released on November 25, adds a PreSkillShellCommand hook event “that can refuse a skill or command’s inline shell commands as it loads”. Those are the !`command` lines in a SKILL.md or a .claude/commands file. Claude Code runs them before Claude sees the skill and pastes their output into the prompt. Until this release, no hook saw them as they ran.

I ran it on 2.1.332 the day after release, headless, in a throwaway repository. The hook works as documented. Two side tests matter more than the hook itself. A skill argument placed inside one of those lines runs as shell at load time, which is why the script below matches exact strings instead of looking for bad words. And a code fence does not keep a line from running, so a skill that only documents the syntax runs its own examples, which is why the script starts as a log: you may not know which lines your skills run. Where a claim rests on the docs alone, it says so.

What does the Claude Code PreSkillShellCommand hook see that PreToolUse doesn’t?

The shell commands a skill runs while it loads. The skills page is direct: “PreToolUse hooks don’t fire for injected commands that run as the skill loads.” I checked it with a positive control: a logging hook on each event and a skill with one injected date line that also asks Claude to run uname -s.

PreToolUse:            Bash uname -s
PreSkillShellCommand:  date -u +%F

Each event got exactly one command. If you run a Bash guard on PreToolUse today, it has never seen a !` line, and the hooks reference says to add the same script to the new event.

Two limits from the docs. The hook runs after the permission check, so it only gets commands your rules already passed, and it runs in bypassPermissions mode too. And it can only refuse: “You can block a command from this hook, but you can’t approve or change one.”

Which Claude Code skills run shell commands as they load?

The ones that want live context before Claude starts. In Anthropic’s own plugin marketplace, the /commit command in commit-commands opens with four:

markdown
- Current git status: !`git status`
- Current git diff (staged and unstaged changes): !`git diff HEAD`
- Current branch: !`git branch --show-current`
- Recent commits: !`git log --oneline -10`

The claude-security skill reads the clock and runs find for earlier reports. Lines like these are read-only and fixed: the same string on every run, which is what lets you pin them.

Does a code fence stop a !command line in a Claude Code skill?

No. The skills page says the inline form is recognized at the start of a line or after whitespace, and documents a separate ```! fence for multi-line commands. It does not say what an ordinary markdown example fence does to an inline line. I wrote a skill whose only !` line sat inside a fenced markdown example, as documentation. The command ran, and Claude got the date in place of the line.

That matters for skills that teach the syntax. The plugin-dev plugin in the same marketplace has a command-development skill whose body is full of example command files in fenced blocks, with !` lines in them. I loaded a copy of it as a project skill. In default mode the copy never loaded: the permission check stopped at one of the examples and aborted the whole invocation.

Shell command permission check failed for pattern "!`npm test $1`":
A variable in this command can't be checked before it runs

In bypassPermissions mode with the hook in place, the hook was asked about fourteen commands, refused all of them, and the skill loaded and answered normally. Among the fourteen:

git diff --name-only
npm test $1
gh pr view $1
node ${CLAUDE_PLUGIN_ROOT}/scripts/analyze.js $1
bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh

I did not run the copy in bypass mode without the hook, and I tested the copy, not the installed plugin, where ${CLAUDE_PLUGIN_ROOT} would point at real paths. By the fenced date test, those lines could run in that mode, npm test among them, in whatever directory the session is in.

Can a Claude Code skill argument run a command at load time?

Yes. $ARGUMENTS, the indexed $0, $1 and named arguments are substituted into the skill text before the injected commands run, and nothing quotes them for the shell. My test skill greet has one line:

markdown
- Greeting: !`echo "Hello, $ARGUMENTS"`

Called in default mode, with the single quotes keeping my own shell out of it:

shell
claude -p '/greet $(echo INJECTED-$((6*7)))' --permission-mode default

The hook logged the command as it would run, and Claude received the result of the substitution:

hook saw:   echo "Hello, $(echo INJECTED-$((6*7)))"
Claude got: - Greeting: Hello, INJECTED-42

That one passed the permission check because the inner command is also echo. Whether a harmful argument gets through depends on your setup. A plain /greet Max loads in default mode with no allowed-tools, so the check is reading the argument, not refusing the skill. I swapped the inner command for touch and ran five combinations:

mode                 allowed-tools   hook        file created
default              none            log only    no, skill aborted at permission check
default              Bash(echo *)    log only    no, skill aborted at permission check
default              Bash(*)         log only    yes
bypassPermissions    none            log only    yes
bypassPermissions    none            allow-list  no, line refused

In default mode the check parses the whole command and names the part inside the substitution, starting with “The following parts require approval: touch pwned-x”. That is the design working. It stops working when the skill pre-approves all of Bash, or when the session runs with permissions off.

In bypass mode Claude could run the same touch through Bash anyway, so why care about this path? My reasoning, not a run: the load path differs in two ways. No model reads the command before it runs, and a PreToolUse guard you rely on in that mode never sees it.

Claude passes arguments too. I told Claude to invoke the skill with $(touch pwned-claude) as the argument. It passed it unchanged, the hook received the command with invoked_by: "claude", and the allow-list refused it. I did not test whether text in an issue or a web page gets Claude to do the same.

The pattern is in Anthropic’s own examples. Besides !`npm test $1` above, a separate examples file in plugin-dev validates an argument under allowed-tools: Bash(*) with this line:

markdown
Validate environment argument: !`echo "$1" | grep -E "^(dev|staging|prod)$" && echo "VALID" || echo "INVALID"`

The validation line is itself where the argument reaches the shell.

Is a deny-list enough for a Claude Code PreSkillShellCommand hook?

No. My first hook was the obvious one: refuse anything that mentions curl, wget, ssh, .env or .ssh/, and after the test above, $( and backticks. Then I passed this argument in bypass mode:

shell
claude -p '/greet x"; touch pwned-quote; echo "' --permission-mode bypassPermissions

The hook received a command with no forbidden word in it, let it through, and the file appeared:

hook saw:  echo "Hello, x"; touch pwned-quote; echo ""

A deny-list has to predict every way to write a command. An allow-list has to know only the few commands a skill really runs, and any argument that changes the string fails the exact match by construction. The same payload against the allow-list came back not in the allow-list for greet. The cost: a skill with an argument in a !` line can be pinned only for the exact argument values you list, and every other value is refused. If you write skills, keep arguments out of !` lines and let Claude handle them in the turn, where PreToolUse and the normal tool-permission checks apply.

How do you write a PreSkillShellCommand hook in Claude Code?

Register a command hook on the event in a settings file, read the JSON on stdin, and exit 2 to refuse. The docs recommend the matcher Bash|PowerShell (both tools that run injected commands), a synchronous command, http or mcp_tool handler, and onFailure: "block" so a crashed script does not wave commands through. Hooks in a skill’s own frontmatter don’t cover its first load, so the hook belongs in settings or a plugin. This is the PreSkillShellCommand entry from my Linux test settings; "args": [] runs the script in exec form, without a shell, so the path needs no quoting (on Windows, exec form needs the interpreter as the command and the script in args):

json
{
  "hooks": {
    "PreSkillShellCommand": [
      {
        "matcher": "Bash|PowerShell",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/skill-shell-allowlist.py",
            "args": [],
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}

The hook receives the common fields plus tool_input.command (the command as it would run), command_name (the skill, or plugin:skill for a plugin), command_source (projectSettings, userSettings, plugin and so on) and invoked_by (user, claude or other). From my run, trimmed:

json
{
  "hook_event_name": "PreSkillShellCommand",
  "permission_mode": "default",
  "tool_name": "Bash",
  "tool_input": { "command": "curl --version" },
  "command_name": "env-check",
  "command_source": "projectSettings",
  "invoked_by": "user"
}

The script logs every command it is asked about, then lets through only the exact strings listed under that skill’s command_name. It keeps the list and the log next to itself:

python
#!/usr/bin/env python3
# PreSkillShellCommand: run an injected command only if it is pinned for that skill.
import json, os, sys
from datetime import datetime, timezone
 
here = os.path.dirname(os.path.abspath(__file__))
event = json.load(sys.stdin)
skill = event.get("command_name", "?")
cmd = event.get("tool_input", {}).get("command", "")
 
with open(os.path.join(here, "skill-shell.log"), "a") as log:
    log.write(json.dumps({
        "at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "skill": skill, "source": event.get("command_source"),
        "invoked_by": event.get("invoked_by"), "command": cmd,
    }) + "\n")
 
if os.environ.get("SKILL_SHELL_MODE") == "log":
    sys.exit(0)
 
try:
    with open(os.path.join(here, "skill-shell-allow.json")) as f:
        allowed = json.load(f).get(skill, [])
    if not (isinstance(allowed, list) and all(isinstance(c, str) for c in allowed)):
        raise ValueError
except (OSError, ValueError, AttributeError):
    print("skill-shell-allow.json missing or malformed", file=sys.stderr)
    sys.exit(2)
 
if cmd in allowed:
    sys.exit(0)
print(f"not in the allow-list for {skill}", file=sys.stderr)
sys.exit(2)

Make it executable with chmod +x: under onFailure: "block" a script that cannot start refuses everything. The list, skill-shell-allow.json in the same folder:

json
{
  "env-check": ["date -u +%F", "git status --short --branch"]
}

My test skill env-check has three injected lines: the two pinned ones and curl --version, which its allowed-tools pre-approved, so the permission check passed it. With the hook on, the skill loaded and Claude received this:

## Environment
- Date: 2026-11-26
- Branch: ## No commits yet on master
?? .claude/
- Curl: [not run: blocked by hook: not in the allow-list for env-check]

That is exit 2: one line refused, the skill still loads (the Claude Code hooks guide covers exit codes and onFailure in general). To stop the whole skill, exit 0 and print {"continue": false, "stopReason": "..."}. My run with that ended at once with Operation stopped by hook: env-check wants the network at load time, and per the docs none of the skill’s injected commands runs then.

Three details from testing. In my headless runs, whatever the script wrote to stderr was the reason Claude read, all of it (per the docs, Remote Control hides the reason): an early version raised a Python DeprecationWarning, and the warning text arrived in Claude’s context inside the block message. Without the try, a missing list fails closed only because of onFailure, and the reason Claude reads is a Python traceback with the full path; with it, every line comes back skill-shell-allow.json missing or malformed, also when a skill’s entry is a string instead of a list (a string would turn the in check into a substring match). And log mode works: with SKILL_SHELL_MODE=log in the environment Claude Code starts from, the same run let curl through and logged all three commands, which is how you collect the strings worth pinning.

Where the files live matters. In my test they sat in the project’s .claude/hooks, where a cloned repository can ship its own list. My reasoning, not a run: in user settings, with the script and list in ~/.claude/hooks, a checkout can no longer supply them. That does not protect them from a session running with permissions off, which can write your user files too; a policy that must hold against the session belongs in managed settings. The list is keyed by command_name only, so at user level a project skill called deploy shares its approvals with every other deploy. And keep the log out of git.

Per the docs and untested here: an interactive session prints Not run in /<name> for a refused line, and on 2.1.331 or older a settings file that names this event opens a warning dialog at the start of each interactive terminal session.

PreSkillShellCommand, permission rules or disableSkillShellExecution: which Claude Code control fits?

A deny rule for a command you never want to match on either path, the hook to decide line by line per skill, and disableSkillShellExecution to turn load-time commands off. I ran each against env-check:

control                              effect on the skill            covers Claude's own Bash calls
deny rule Bash(curl *)               whole skill aborts             yes
PreSkillShellCommand hook (exit 2)   one line refused, skill loads  no
disableSkillShellExecution: true     every line replaced            no

The deny rule ended the run before Claude saw the skill, in default and in bypassPermissions mode alike:

Shell command permission check failed for pattern "!`curl --version`":
Permission to use Bash with command curl --version has been denied.

A deny rule is also a list of names, matched against the command text, so it stops only what you named. It is still worth having: it parses the command, as the touch inside $( showed, and the same rule stops Claude from running curl later in the session. With disableSkillShellExecution, every line arrived as [shell command execution disabled by policy] and the hook was never called. Per the docs, bundled and managed skills keep running theirs.

Shell lines in skills served by MCP servers never reach any of the three. Per the docs, !` commands in an MCP skill “don’t run” (permission rules can still block the MCP skill itself), and claude -p does not support MCP skills, so I could not test them. An MCP skill can still tell Claude what to run, and that goes through the normal tool path.

Does PreSkillShellCommand cover the skill attacks the ClawHub study measured?

Mostly not. A preprint posted on November 23 studied 48,682 skills on ClawHub, a public skill registry. In its live-agent run, the agent executed an injected payload in 97 of 200 sampled flagged skills (48.5%), “almost always in its own shell before the skill runs”. That agent was gpt-4o-mini with a tool that runs commands through bash -c, and the path is the agent filling a skill’s documented command with attacker text. In Claude Code that is a Bash tool call, which is PreToolUse and permission territory. The abstract concludes that “agent runtimes should not pass skill arguments through a shell”. Reading that next to the greet test is my inference, not theirs: $ARGUMENTS inside a !` line is the same mistake made at load time, and when permissions are open, the new hook is the only control that looks at that line before it runs.

What should you set up for Claude Code skill shell commands, and in what order?

  1. Update to 2.1.332 first. Older versions run injected commands without calling the hook.
  2. Find the candidate lines. This lists !` lines in the usual folders, fenced ones included, plus examples in supporting files that never load, so check the surrounding text and later the hook log:
    shell
    grep -rnE '(^|[[:space:]])!`|^```!' .claude/skills .claude/commands \
      ~/.claude/skills ~/.claude/commands ~/.claude/plugins 2>/dev/null
    Rewrite any line of your own that contains $ARGUMENTS, $0, $1 or a named argument so Claude handles the argument in the turn.
  3. Add the hook in log mode with onFailure: "block". Use the skills you rely on for a few days.
  4. Pin and switch log mode off. Every legitimate line from the log goes into the list under its command_name.
  5. Keep the hard rules in permissions. A deny rule covers both the load path and Claude’s own calls; the hook is the layer on top.

None of this tells you whether a third-party skill is honest. That was the problem in the skills supply-chain post, and it still is. For the older side of the same feature, how a failed !` line aborts a skill while claude -p exits 0, see the slash commands post. What the hook adds is a record of every load-time command that got past your permission rules, and a way to refuse the ones you never agreed to.

01 / Discussion

No comment section here — all discussions happen on X.

Max Nardit@mnardit

02 / More articles