skip to content

Headless Mode

Scripting with -p: choose an output format to parse, pre-approve tools or set a permission mode since nobody answers prompts, and cap turns and spend. Asked because unattended runs hang or fail open.

part ofClaude Coderead it →
on this pageshow

explore

questions

6

What does `claude -p` do, and how does a shell script feed it input and tell whether the run succeeded?

level: juniorimportance: must knowfreq 30%

answer

  1. one prompt in, one answer out
  2. no terminal interface, same agent loop
  3. stdin in, stdout out
  4. text is the default format
  5. branch on the exit status, not stdout

basics

~10 s

claude -p (alias --print) runs Claude Code non-interactively: it takes the prompt plus any piped stdin, runs the agent loop, prints the result to stdout, and exits 0 on success or non-zero on failure.

solid answer

~40 s

`claude -p "prompt"` (or `--print`) runs the same agent loop and tools as an interactive session, but with no terminal interface: Claude works the task, prints the final response and exits. It reads stdin, so `cat build-error.txt | claude -p 'explain the root cause' > out.txt` behaves like any Unix filter; piped stdin is capped at 10MB. The default `--output-format` is `text`; a script that needs fields asks for `json`. Claude Code exits 0 on success and non-zero when the run fails, so the script branches on the exit status. An invalid flag is reported on stderr before the run starts, but a failure inside the run, such as missing authentication, is printed as the result on stdout, so text on stdout does not mean success.

code

bash · 7 lines
bash
#!/usr/bin/env bash
if git diff main | claude -p "Report each typo in this diff as file:line, then the issue. Return nothing else." > typos.txt; then
  echo "typo report written to typos.txt"
else
  echo "claude -p failed; typos.txt holds the reported error, not a review" >&2
  exit 1
fi

go deeper

for a junior

Recall that -p is --print, that it runs the full agent non-interactively, reads stdin, prints text by default and exits 0 on success or non-zero on failure.

for a middle

Explain where each failure surfaces: invalid flags on stderr before the run, in-run failures as the result on stdout, plus the 10MB stdin cap and when to switch to json output.

for a senior

Show a script that never commits an error message as an answer: branch on the exit status, pipe data in instead of granting tools, and handle SIGTERM's exit code 143 in supervisors.

for a principal

Argue when a team should wrap claude -p in plain scripts versus moving to the Agent SDK library, weighing parse effort, error handling and how many unattended jobs depend on it.

## What print mode is **Print mode** is Claude Code's non-interactive way of running. You add `-p` (long form `--print`) to a `claude` command and pass the prompt as an argument: ```bash claude -p "What does the auth module do?" ``` Nothing about the agent changes: Claude still reads files, edits them and runs shell commands through the same tools and the same **agent loop** as an interactive session. What disappears is the terminal interface. There is no input box, no mode indicator and nobody watching, so the run takes one prompt, works until Claude produces a final response, prints that response and exits. That makes `claude -p` a building block for shell scripts, `package.json` scripts, cron jobs and CI steps. Not every flag combines with it. Claude Code rejects `--bg` with `-p`, for example, and reports the conflict instead of starting. ## Feeding it input A script can give `claude -p` input in two ways: - **The prompt argument**, the instruction itself. - **Standard input.** Print mode reads stdin, so you can pipe data in: `git diff main | claude -p "report each typo as file:line"`. Piping the diff also means Claude does not need permission to run `git diff` itself. Piped stdin is **capped at 10MB**. Above the cap, Claude Code exits with a clear error and a non-zero status. For larger inputs, write the content to a file and name the file in the prompt; Claude reads it with its file tools, and reading files in the working directory needs no approval. Prompts can also invoke user-invoked skills and custom commands: put `/skill-name` in the prompt string and Claude Code expands it before running. Built-in commands that exist only in the terminal interface, such as `/login`, are not available. ## Reading its output | `--output-format` | What stdout carries | Use it when | | --- | --- | --- | | `text` (default) | The final response as plain text | A human reads it, or it goes straight into a file | | `json` | One JSON object with `result`, `session_id`, cost and usage | A script needs fields | | `stream-json` | Newline-delimited JSON events, ending with a `result` message | Something consumes progress live | A script that only needs the answer can redirect `text` output to a file. A script that needs the session ID, the cost or structured data asks for `json` and parses it. ## Exit status and where errors go This is where scripts most often go wrong. Claude Code reports problems in different places depending on when they happen: 1. **Before the run starts**: an invalid flag or option is reported on **stderr**, and the process exits non-zero. 2. **During the run**: a failure such as missing authentication is printed **as the result on stdout**, and the process exits non-zero. 3. **On success**: the response goes to stdout and the exit status is **0**. Two more cases matter for long jobs: a run that hits a `--max-turns` limit exits with an error, and a run stopped with SIGTERM (from `kill` or a process supervisor) exits with code **143**, leaving the turn in progress unfinished. The consequence of point 2 is that **the presence of text on stdout says nothing about success**. If your script does `claude -p ... > review.md` and then commits `review.md`, a failed run can commit an error message. Check the exit status first, and with `--output-format json` read the result fields rather than the raw text. ## What print mode does not do - **It does not wait at a terminal for approvals.** Nobody can answer a permission prompt, so tools must be pre-approved or a permission mode chosen for the run. - **It does not show the workspace trust dialog**, so without `--bare` a `-p` run loads the project's hooks and MCP servers as an interactive session would. - **It does not cap itself.** There is no turn limit by default; `--max-turns` and `--max-budget-usd` add caps. ## A minimal pattern - Pipe the data in rather than granting a tool to fetch it. - Redirect stdout to a file, but decide what to do with that file from the exit status. - Switch to `--output-format json` as soon as the script needs anything more than the text.

  • Why can a failed `claude -p` run leave an error message in the file you redirected stdout to?
    Only errors detected before the run starts, such as an invalid flag, go to stderr. A failure inside the run, such as missing authentication, is printed as the result on stdout, and the process exits non-zero. So the redirected file can hold an error; a script decides from the exit status, or from the parsed JSON result, whether the file is a real answer.
  • How do you give `claude -p` more input than it accepts on stdin?
    Piped stdin is capped at 10MB, and exceeding it makes Claude Code exit with an error and a non-zero status. Write the data to a file instead and name the path in the prompt, so Claude reads it with its file tools; reads inside the working directory need no approval.
  • Can a `claude -p` prompt run a slash command?
    Partly. User-invoked skills and custom commands work: include `/skill-name` in the prompt string and Claude Code expands it before the run. Built-ins that only exist in the terminal interface, such as `/login`, are unavailable, and a few such as `/model` take their value as an argument, for example `/model sonnet`.

  • claude -p is a plain model call with no tools or agent loop
  • If stdout has text, the run succeeded, so the exit status can be ignored
  • Every claude -p error goes to stderr, so stdout is always the answer
  • claude -p pauses at the terminal to let you approve each tool call
  • Piped stdin has no size limit, so whole log archives can be streamed in
open as a page

A nightly `claude -p` lint-triage job must neither stall on a permission prompt nor run commands nobody approved; how do you set its permissions?

level: seniorimportance: must knowfreq 20%

basics

~20 s

Pass the mode explicitly, usually --permission-mode dontAsk with narrowly scoped --allowedTools rules, so anything unlisted is denied rather than prompted; add --permission-prompts none (2.1.259+) when a permission host could otherwise wait, and never a bare Bash allow.

open as a page

How do `--max-turns` and `--max-budget-usd` cap a `claude -p` run, and what does each count or leave out?

level: middleimportance: should knowfreq 12%

basics

~20 s

--max-turns limits agentic turns and exits with an error when reached; --max-budget-usd stops the run once estimated spend, subagents included, hits the cap. Both are print-mode only; neither has a default, and resumed spend is not counted.

open as a page

In `claude -p`, when do you choose `--output-format json`, `stream-json` or `--json-schema`, and what does a script read from each?

level: middleimportance: should knowfreq 15%

basics

~10 s

Use json for one final object a script parses (result, session_id, total_cost_usd), stream-json for newline-delimited events while the run progresses, and --json-schema with json output when you need validated data in structured_output.

open as a page

What does `claude -p --bare` skip at startup, and why do Claude Code's docs recommend it for scripts and CI?

level: seniorimportance: should knowfreq 11%

basics

~20 s

--bare skips auto-discovery of hooks, skills, custom commands, subagents, plugins, MCP servers, auto memory and CLAUDE.md, so a scripted run starts faster, behaves the same on every machine and runs no repository config it was not handed.

open as a page

In a multi-step `claude -p` script, why capture `session_id` and pass `--resume` rather than chaining calls with `--continue`?

level: middleimportance: nice to knowfreq 7%

basics

~20 s

--continue picks the most recent conversation in the current directory, so concurrent jobs can grab each other's session; --resume with the session_id read from --output-format json targets exactly one conversation, from any directory on the machine.

open as a page