Skip to content
Academy ofAI Learning

~/academy $ claude learn headless-and-scripting

Headless mode: Claude Code in scripts

Run Claude Code non-interactively with -p, pipe data in, get text or JSON out, and cap turns, tools and spend so scripts stay safe and predictable. 8 min

Watch it done: run Claude Code from a script with -p

$

Step 1 of 7

Open a terminal in your project. These commands use bash syntax, and the JSON steps need jq installed.

  1. Open a terminal in your project. These commands use bash syntax, and the JSON steps need jq installed. Type: cd ~/projects/my-app.
  2. Add -p (short for --print) and Claude Code runs one task with no chat window, which is what makes it usable in scripts, cron jobs and CI. Type: claude -p "What does the auth module do?". Claude prints its answer and exits. The exit code is 0 on success and non-zero on failure, so a script can check it.
  3. Pipe data in and redirect the answer out. Piped input is capped at 10MB, so for bigger files put the path in the prompt instead. Type: cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt. Nothing prints in the terminal. The explanation is saved in output.txt.
  4. Ask for JSON so a script can read the answer reliably instead of scraping text. Type: claude -p "Summarise this project" --output-format json | jq -r '.result'. The JSON holds the answer in result, plus session_id and an estimated total_cost_usd. jq prints just the answer.
  5. Nobody is there to answer permission prompts, so pre-approve exactly the tools the job needs and cap the number of turns. Type: claude -p "Run the test suite and fix any failures" --allowedTools "Bash,Read,Edit" --max-turns 10. Since version 2.1.302, a -p run with no permission mode set starts in Manual mode, so any other call that needs approval is denied.
  6. Start a run and keep its session ID in a shell variable, so you can return to that exact conversation. Type: session_id=$(claude -p "Start a review of src/" --output-format json | jq -r '.session_id').
  7. Resume the saved run with a follow-up. Use --continue instead if you just want the most recent conversation. Type: claude -p "Now list only the security issues" --resume "$session_id". Claude carries on the same conversation, with the earlier review already in context.

Commands from the official Claude Code headless and CLI reference docs, checked 18 November 2026. File names such as build-error.txt stand for files in your own project. Lines marked Note describe what happens and are not real output.

Step 1 of 6

$ Read

Print mode in one line

Add -p (or --print) and Claude Code runs one task, prints the answer and exits. No chat window, so you can call it from shell scripts, npm scripts, cron jobs and CI.

It reads standard input, so you can pipe data in and redirect the answer out. Piped input is capped at 10MB; for bigger files, pass the path in the prompt instead. It exits with 0 on success and a non-zero code on failure, so scripts can branch on it.

Ask a question
claude -p "What does the auth module do?"
Pipe a log in, save the answer
cat build-error.txt | claude -p 'explain the root cause of this build error in three lines' > output.txt
As an npm script
"lint:claude": "git diff main | claude -p \"report any typos in this diff as filename:line\""

Lesson notes: Headless mode: Claude Code in scripts

Everything in this lesson as text, for revision or to read without the interactive steps. By the end you will be able to: You run Claude Code from a script, parse its JSON output and limit what it is allowed to do.

  1. Step 1 of 6 · Read

    Print mode in one line

    Add -p (or --print) and Claude Code runs one task, prints the answer and exits. No chat window, so you can call it from shell scripts, npm scripts, cron jobs and CI.

    It reads standard input, so you can pipe data in and redirect the answer out. Piped input is capped at 10MB; for bigger files, pass the path in the prompt instead. It exits with 0 on success and a non-zero code on failure, so scripts can branch on it.

    Ask a question
    claude -p "What does the auth module do?"
    Pipe a log in, save the answer
    cat build-error.txt | claude -p 'explain the root cause of this build error in three lines' > output.txt
    As an npm script
    "lint:claude": "git diff main | claude -p \"report any typos in this diff as filename:line\""
  2. Step 2 of 6 · Read

    Output a script can read

    --output-format takes text (the default), json or stream-json. With json you get the answer in result, plus session_id and total_cost_usd. The cost is an estimate worked out on your machine, not your bill.

    Add --json-schema with a JSON Schema and the structured answer arrives in structured_output. If Claude declines or the run fails, that field is missing, so check for it before you use it.

    Just the text
    claude -p "Summarise this project" --output-format json | jq -r '.result'
    Structured output
    claude -p "List the main function names in auth.py" \
      --output-format json \
      --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
      | jq '.structured_output'
  3. Step 3 of 6 · Try it in the terminal

    Get JSON back

    Run Claude Code in print mode with the prompt "Summarise this project" and ask for JSON output.

    Hint: claude -p, the prompt in quotes, then --output-format json.

    Show the command
    $ claude -p "Summarise this project" --output-format json
    {"type":"result","subtype":"success","is_error":false,"result":"A Next.js web app for booking salon appointments, with a Postgres database and Stripe checkout.","session_id":"4f2c1d9e-7b3a-4c1e-9a55-2e8f0c6b1d77","num_turns":3,"total_cost_usd":0.041}
  4. Step 4 of 6 · Read

    Limit what it can do

    A script has no one to answer permission prompts. Since version 2.1.302, a -p run with no mode set starts in Manual mode, and anything that would need your approval is denied (checked 18 November 2026). So grant exactly what the job needs.

    --allowedTools pre-approves tools using permission rule syntax, such as Bash(git diff *). --disallowedTools denies them. --tools limits which built-in tools exist at all. --max-turns stops after a set number of agent turns and --max-budget-usd stops when estimated spend reaches a cap. Both work in print mode only.

    Fix tests, nothing else
    claude -p "Run the test suite and fix any failures" --allowedTools "Bash,Read,Edit" --max-turns 10
    Commit, with git only
    claude -p "Look at my staged changes and commit them" \
      --allowedTools "Bash(git diff *),Bash(git status *),Bash(git commit *)"
    Hard cap on spend
    claude -p --max-budget-usd 2.00 "Review the open TODOs in src/"
  5. Step 5 of 6 · Read

    Same result on every machine

    Without extra flags, claude -p loads hooks, skills, plugins, MCP servers and CLAUDE.md just like a normal session, including anything in the project folder. It also skips the workspace trust dialog, so a repository's hooks and .mcp.json servers can run.

    --bare skips all of that for a fast, predictable start, and the docs recommend it for scripts. Bare mode does not use your subscription login, so set ANTHROPIC_API_KEY first. Add back only what you need with flags such as --mcp-config or --append-system-prompt.

    To keep a conversation going, --continue picks up the latest one. To return to a specific run, save its session_id from the JSON and pass it to --resume.

    Bare and read-only
    claude --bare -p "Summarise README.md" --allowedTools "Read"
    Resume a specific run
    id=$(claude -p "Start a review of src/" --output-format json | jq -r '.session_id')
    claude -p "Now list only the security issues" --resume "$id"
  6. Step 6 of 6 · Quiz

    Check your understanding

    A nightly script runs claude -p on a repository you did not write. Which setup is safest?

    • claude -p with --dangerously-skip-permissions so nothing blocks it
    • claude --bare -p with --allowedTools listing only what the job needs, and --max-turns
    • claude -p with no flags, because print mode shows a trust dialog
    • An interactive session left open overnight
    Show the answer

    claude --bare -p with --allowedTools listing only what the job needs, and --max-turns Bare mode skips the repository's hooks, MCP servers and CLAUDE.md, and the allowlist and turn cap keep the job narrow.