Skip to content

Claude Code guide in three levels, Beginner to Advanced: hands-on lessons with checked exercises, every volatile fact cited to its source. Independent community guide.

16.1 KB
Raw Blame

Script Claude Code with claude -p

Advanced · Lesson 4 of 7 · about 20 minutes · Needs: Run and save a dynamic workflow · Verified against Claude Code v2.1.308 (stable) on 2026-10-25

Goal

By the end of this lesson you can write a script that runs Claude Code with no one at the keyboard, reads its JSON result and exit code, gets an answer in a shape you define, and limits the run to the tools and turns the job needs.

You need

  • One of your own repositories with a test command, and your copy of the practice template with Node.js LTS: the check runs from the copy. To practice in the template copy instead, use it for both. Set up the repository's .practice/ folder as the Intermediate index describes, if you haven't yet.
  • bash and jq, on macOS, Linux or WSL 2.
  • Usage: light. Each claude -p run is one short session.

The idea

claude -p "<prompt>" runs one prompt without the interactive interface, prints the answer and exits with 0, or non-zero when the run fails (Run Claude Code programmatically). It reads stdin, so a script can pipe a diff in.

With --output-format json, it prints one JSON object with result, is_error, num_turns, session_id and permission_denials (SDKResultMessage). result holds the answer, or the failure message when something fails inside the run (Basic usage). subtype is success, or why the run stopped early, such as error_max_turns; such a run has no result (Handle the result). Check the exit code and is_error before you use result.

When a script needs fields rather than prose, add --json-schema with a JSON Schema: the object then also holds structured_output, an answer in that shape (Get structured output). A run that ends without valid structured output has no structured_output field, so check that it's there before you use it.

Nobody can answer a permission prompt, so pass a mode every time, and the script behaves the same on every version. Since v2.1.302, a run that sets none starts in Manual mode and denies every call that needs approval; before that, it could start in auto mode (Tool calls denied in claude -p and Agent SDK runs). Three flags set the limits: --permission-mode dontAsk denies every call that would otherwise prompt, --allowedTools names what may run anyway, and --max-turns caps the turns. --tools goes further: it restricts which built-in tools Claude can use at all (CLI flags).

A -p run also loads what an interactive session would: hooks, skills, plugins, MCP servers and CLAUDE.md, from the project and from ~/.claude. In CI, where the run has an API key, add --bare, which skips all of them so every machine behaves the same (Start faster with bare mode). This lesson runs on your own login, which --bare never reads, so its steps use --setting-sources user to leave the project's settings files and .mcp.json out (What runs before you trust a folder).

Worked example

In your repository:

  1. Ask for two facts a script can read, and save the JSON:

    claude -p "What does this repository do, in one sentence, and what command runs its tests?" --output-format json --permission-mode dontAsk --json-schema '{"type":"object","properties":{"summary":{"type":"string"},"test_command":{"type":"string"}},"required":["summary","test_command"]}' > .practice/a-4-first.json
    echo "exit $?"
    jq '{is_error, subtype, num_turns, session_id}' .practice/a-4-first.json
    jq '.structured_output' .practice/a-4-first.json
    

    It prints exit 0, then "is_error": false and "subtype": "success" with a turn count and a session ID, then an object with a summary and a test_command, such as "npm test" (your values will differ). A script reads one field, as jq -r '.structured_output.test_command // empty' does, and stops when it comes back empty. Reading files in your working directory needs no approval, so dontAsk let Claude read what it needed (dontAsk mode).

  2. Ask for something that needs approval. --setting-sources user keeps your project's settings files out of the run (CLI flags), so neither the allow rule nor the sandbox's auto-allow mode from Intermediate lesson 4 approves the test command (Auto-allow mode). It also leaves out the project's deny rules, such as your .env rules from that lesson, so steps 2 to 4 pass them again with --disallowedTools, which takes deny rules (CLI flags):

    claude -p "Run the test suite and say how many tests pass" --output-format json --permission-mode dontAsk --setting-sources user --disallowedTools "Read(./.env)" "Read(./.env.*)" > .practice/a-4-denied.json
    jq -c '.permission_denials[] | {tool_name, command: .tool_input.command}' .practice/a-4-denied.json
    jq -r .result .practice/a-4-denied.json
    

    Each line is a call that dontAsk denied (SDKPermissionDenial), such as {"tool_name":"Bash","command":"npm test 2>&1 | tail -20"}; Claude picks the command, so yours may differ. The result says Claude couldn't run the tests (your wording will differ).

  3. Allow the command step 2 listed (here npm test), and cap the turns:

    claude -p "Run the test suite and say how many tests pass" --output-format json --permission-mode dontAsk --setting-sources user --disallowedTools "Read(./.env)" "Read(./.env.*)" --allowedTools "Bash(npm test *)" --max-turns 3 | jq '{subtype, num_turns, denied: (.permission_denials | length)}'
    

    It shows "subtype": "success" and "denied": 0: this time Claude ran the tests. The space before the * matters, and a trailing * also matches the bare command (Wildcard patterns). A rule must match each part of a pipeline Claude writes, such as npm test 2>&1 | tail -20, where tail is a read-only command that needs no rule (Compound commands, Read-only commands).

  4. Hit the cap. This task takes two steps in a row, and --max-turns 1 allows one turn that calls tools. Keep Read and use the same Bash rule as in step 3:

    claude -p "Read the file that defines this project's test command, then run that command, then summarize any failures" --output-format json --permission-mode dontAsk --setting-sources user --disallowedTools "Read(./.env)" "Read(./.env.*)" --allowedTools "Read,Bash(npm test *)" --max-turns 1 > .practice/a-4-capped.json
    echo "exit $?"
    jq '{subtype, has_result: has("result")}' .practice/a-4-capped.json
    

    It prints a non-zero exit code, then "subtype": "error_max_turns" and "has_result": false: a run that stops at the cap has no result. --max-turns counts only the turns that call tools (Turns and messages), so if the run finished, give it a task with more steps.

Your turn

Build a pre-commit reviewer that runs nothing you didn't allow and never hides a failed run. scripts/review-staged.sh sends your staged changes to Claude, prints Claude's review and saves the JSON result. The Advanced capstone reuses it.

Acceptance criteria:

  • A bash script at scripts/review-staged.sh, committed and executable.
  • It pipes git diff --cached, the staged changes (git diff), into one claude -p call. Claude needs no Bash to read the diff, because it arrives on stdin (Add Claude to a build script).
  • That call puts the prompt right after -p, as the Pipe data through Claude and Add Claude to a build script examples do, and passes --output-format json, --permission-mode dontAsk, --allowedTools naming only Read, Grep and Glob, and --max-turns with a number from 1 to 10. On macOS, Linux and WSL, Glob and Grep are absent by default, and naming either one in --allowedTools brings both back (Glob tool behavior). --allowedTools only pre-approves: a tool it doesn't name still runs when a rule approves it, such as the test rule from Intermediate lesson 4. So the call also passes --tools "Read,Grep,Glob", which restricts the built-in tools to those three, so Claude can't use Bash, Edit or Write at all (CLI flags).
  • It keeps the project's hooks and MCP servers out of the review. --settings '{"disableAllHooks": true}' turns hooks off for the run, so the Stop hook from Intermediate lesson 5 can't send the reviewer back to work (Disable or remove hooks), and --strict-mcp-config uses only the MCP servers you pass with --mcp-config, here none (Project scope). Unlike --setting-sources user, both keep the project's skills, so the capstone's review skill still loads (Control filesystem settings with settingSources).
  • It saves the JSON to the path in its first argument, or to .practice/a-4-result.json when it gets none, creating the folder if it's missing.
  • It prints the result text, and exits non-zero when claude does or when is_error is true.
  • With nothing staged, it says so and exits non-zero without calling Claude. git diff --cached --quiet exits with 0 when nothing is staged (git diff).

Commit the script. Then stage a small change, such as a one-line fix, and run scripts/review-staged.sh once: it saves .practice/a-4-result.json. Read the review before you commit that change, and act on it: fix one point it raises, or be able to say why you dismiss it.

Check

You are done when all of these are true:

  • scripts/review-staged.sh is committed and executable.
  • Its claude -p call has the prompt right after -p, asks for JSON, runs in dontAsk mode, pre-approves only Read, Grep and Glob, restricts the tools to those three, turns hooks off and uses no MCP server, and caps turns at 10 or fewer.
  • It pipes the staged diff in, saves the JSON where its argument says, prints the result, exits non-zero when the run fails, and doesn't call Claude when nothing is staged.
  • .practice/a-4-result.json holds a run that succeeded within your cap.
  • Self-check (not tested): you read the review of your staged change and fixed one point it raised, or can say why you dismissed it, before you committed.

Run npm run check -- a-4 --dir <your repo> from your practice copy, or npm run check -- a-4 in the copy itself. The check runs your committed script with a stand-in for claude, so it uses none of your usage.

If the first item fails, run chmod +x scripts/review-staged.sh, then git add it and commit again. If the second item fails, compare your claude -p line with the criteria in Your turn, starting with where the prompt sits. If the third item fails, run the script by hand with nothing staged and again with a staged change, and run echo $? after each; the check runs the committed script, so commit each fix first. If the fourth item fails, stage a change and run the script again: a run that stopped at your cap doesn't count.

Watch out

  • A -p run shows no trust dialog: it runs the hooks in a project's .claude/settings.json and connects the servers in its .mcp.json, even in a folder you've never trusted (Start faster with bare mode). Before you script Claude Code in a repository you didn't write, pass --setting-sources user, so Claude Code reads neither the project's settings files nor its .mcp.json (What runs before you trust a folder). In a run with an API key, --bare keeps them out too.
  • When ANTHROPIC_API_KEY is set, a -p run always uses that key instead of your plan (Authentication precedence). The JSON's total_cost_usd is a client-side estimate, not your bill (Track cost and usage).
  • In a folder you've never trusted, a -p run ignores the permissions.allow rules in the project's .claude/settings.json and prints a this workspace has not been trusted warning on stderr; trusting a parent folder doesn't count (Project allow rules and workspace trust, Error reference). Pass the rules a script needs on its command line, with --allowedTools.

Go further


Sources: Run Claude Code programmatically · CLI reference · Choose a permission mode · Configure permissions · Configure the sandboxed Bash tool · How the agent loop works · Agent SDK reference - TypeScript · Track cost and usage · Authentication · Tools reference · Hooks reference · Connect Claude Code to tools via MCP · Use Claude Code features in the SDK · Error reference · git diff

← Run and save a dynamic workflow · Advanced index · GitHub Actions → · Topic: Automation · Stuck on this lesson?