Back to Blog

Claude Code headless mode: run claude -p from scripts, with output you can parse and a cap on spend

Alex Kim
12 min read
Claude Code headless mode: run claude -p from scripts, with output you can parse and a cap on spend

Last updated: November 19, 2026

TL;DR

Headless mode is claude -p "<prompt>": Claude Code runs the prompt, prints the result and exits, so a script, a cron job or a pipeline can call it. A run you can trust without watching it needs four settings on top of -p (Anthropic's headless docs):

  • ๐ŸงŠ Bare mode, so the run ignores whatever hooks, plugins, MCP servers and CLAUDE.md happen to sit on the machine.
  • ๐Ÿ” Pre-approved tools or a permission mode, because a headless run has nobody to answer a prompt and denies what nothing approves.
  • ๐Ÿงพ JSON output, so your script reads a result field, a session ID and a cost estimate instead of scraping text.
  • ๐Ÿ›‘ A cap on turns and on spend, because neither has a limit by default.

A note on spelling: every long flag below takes two hyphens before its name, as the CLI reference writes it. We name them without the hyphens, so output-format here is the output-format flag with two hyphens in front.

Before you start

Three things decide whether your first run works:

  • How the run signs in. Bare mode never reads your subscription login or the system keychain. Set ANTHROPIC_API_KEY with a key from the Claude Console, or supply an apiKeyHelper in the settings you pass in. Bedrock and the other cloud providers keep reading their own credentials. claude setup-token generates a long-lived OAuth token for CI and scripts from a Claude subscription, and prints it without saving it. Bare mode never reads OAuth credentials, so plan on an API key for bare runs.
  • Your version. Several behaviors below arrived recently: the permission-prompts flag needs v2.1.259 or later, and since v2.1.302 a -p run starts in Manual mode when nothing sets a permission mode. Run claude update on the machine that will run the script.
  • What the job is. One prompt that finishes is headless mode. A prompt that should rerun on a clock while a session stays open is /loop, and "keep going until the tests pass" is /goal.

Step 1: Run one prompt

Add -p (the long form is the print flag) to any claude command:

claude -p "What does the auth module do?"

Non-interactive mode reads stdin, so you can pipe data in and redirect the answer out:

cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt

Piped stdin is capped at 10MB. Past that, Claude Code exits with an error and a non-zero status, so write large inputs to a file and name the file in the prompt instead.

Your script can branch on the exit code: 0 on success, non-zero when the run fails. An invalid flag is reported on stderr before the run starts. A failure inside the run, such as missing authentication, is printed as the result on stdout, so check the exit code rather than looking for an error message.

Not every flag combines with -p. Claude Code rejects bg, and rejects cloud with a task description, with an error naming the conflict.

Step 2: Make the run repeatable with bare mode

Without the bare flag, claude -p loads hooks, skills, custom commands, subagents, plugins, MCP servers, auto memory and CLAUDE.md the way an interactive session would, from the working directory and from ~/.claude. That has two costs:

  • The same command behaves differently per machine. A hook in a teammate's ~/.claude runs on their laptop and not in CI.
  • A repository's own config runs untrusted. A -p session 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, with no trust dialog and no per-server approval.

Bare mode skips all of that. Anthropic calls it the recommended mode for scripted and SDK calls, and says it will become the default for -p in a future release. In bare mode Claude has the Bash, file read and file edit tools, and you hand in anything else by flag:

To loadFlag (two hyphens before each)
Extra system prompt textappend-system-prompt, append-system-prompt-file
Settingssettings with a file or JSON
MCP serversmcp-config with a file or JSON
Custom agentsagents with a file or JSON
A pluginplugin-dir, plugin-url

Three limits come with it:

  • Hooks don't run, even ones you pass in through settings or a plugin. A job that depends on a hook can't use bare mode. Our hooks guide covers what you'd lose.
  • No background work. Claude can't start background commands or background subagents, and a command that hits its timeout stops instead of moving to the background.
  • No system reminders. Claude isn't told when a file it edited changes on disk, and it doesn't get the list of available skills.

Before v2.1.286 these limits held only partly, which is one more reason to update first.

Step 3: Decide what the run may do

A headless run has nobody to answer a permission prompt. In a Manual mode -p run, a call that needs approval is denied unless something approves it. Calls that need no approval, such as reading files in your working directories, still run. You have two ways to approve the rest.

List tools. The allowedTools flag takes permission rule syntax. The docs' commit example allows exactly the git commands the job needs:

allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

Mind the space before the star: Bash(git diff *) matches git diff with or without arguments, while Bash(git diff*) also matches git diff-index.

Set a baseline mode with the permission-mode flag:

ModeWhat a headless run does
dontAskDenies every call that would otherwise prompt. Calls your allow rules cover still run. Suits a locked-down CI job
acceptEditsWrites files without asking and auto-approves common filesystem commands such as mkdir, touch, mv and cp. Other shell commands and network requests still need an allow rule
autoA classifier reviews most actions instead of you

For a scheduled job, add the permission-prompts flag with the value none. Anything that would prompt is then denied unless a PermissionRequest hook allows it, Claude is told nobody can approve it and not to retry, and the run continues. It matters most when your run has a permission host, such as an Agent SDK app with a canUseTool callback; without the flag, the run waits for that host to answer. To make the same choice stick across runs, set permissions.denyInsteadOfPrompting to true in your user or managed settings.

Step 4: Get output a script can read

The output-format flag takes three values:

ValueWhat you get
textPlain text, the default
jsonOne object with the text in result, plus the session ID and metadata, including total_cost_usd and a per-model cost breakdown
stream-jsonNewline-delimited JSON events as the run happens. The last line is a result message with the final text, cost and session metadata

To get data in a fixed shape, pair JSON output with the json-schema flag and a JSON Schema. The answer lands in a structured_output field. If the run ends without valid structured output, for example because Claude declined, that field is missing, so check for it before your script reads it. An invalid schema stops claude with an error that names the flag and the validator's diagnostic. The format keyword is accepted but not enforced.

For live progress, use stream-json with the verbose flag, and add include-partial-messages to receive tokens as they're generated. In stream-json, the first event is usually system/init, which lists the model, tools, MCP servers and plugins. A CI job can fail itself when plugin_errors or mcp_server_errors is non-empty, since a server that fails validation is skipped and the run still exits cleanly.

The cost figures are client-side estimates and can differ from your bill.

Step 5: Cap the run

Two flags stop a run that goes further than you meant. Both work in print mode only:

  • max-turns limits the number of agentic turns. There's no limit by default.
  • max-budget-usd stops the run once estimated spend reaches the amount you set. Spend from subagents counts toward it. It's checked against the same client-side estimate, and spend can pass the cap, so leave headroom. Once the cap is reached, starting another subagent fails with Budget limit reached and running background subagents are stopped (v2.1.217 or later).

One more limit applies whether you set it or not. After Claude's last turn, a -p run waits for background work it started: background commands, subagents, Monitor watches and pending /loop wakeups. Unless a background command the main conversation started is still running, Claude Code stops what's left after 10 minutes of idle waiting and drops its partial result. Change the 10 minutes with CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS, or set it to 0 to wait without a cap. A run that reaches its budget cap stops the remaining background work instead of waiting.

Step 6: Continue a run, or leave no trace

To send a follow-up, run claude -p again with the continue flag for the most recent conversation, or with resume and a session ID for a specific one. The session ID comes from session_id in the JSON output, and resume finds it from any project on the same machine. With continue or resume, the cost in the output is the conversation's whole total, earlier runs included.

For one-off jobs whose history you don't want on disk, the no-session-persistence flag keeps the session from being saved, so it can't be resumed.

Stop a run cleanly

A process supervisor that sends SIGTERM gets exit code 143. Claude Code kills any Bash command still running, runs SessionEnd hooks and exits, leaving the turn in progress unfinished with no result. To let the turn end instead, send SIGINT first, or call the Agent SDK's interrupt().

Troubleshooting

SymptomLikely causeFix
Works on your laptop, fails in CIThe laptop loads local hooks, plugins or MCP serversUse bare mode and pass in what the job needs
Bare mode fails to authenticateBare mode doesn't read your login or keychainSet ANTHROPIC_API_KEY, or an apiKeyHelper in the settings you pass in
Edits or commands are silently deniedManual mode with nothing to approve themAdd allow rules, or set a permission mode
The run hangs on a permission requestAn SDK or MCP permission host isn't answeringAdd the permission-prompts flag with none
structured_output is missingThe run ended without valid outputCheck for the field before reading it
A hook you rely on didn't fireHooks never run in bare modeDrop bare mode for that job
Exit 0, but a long subagent command never finishedThe command moved to the background at its timeoutRaise BASH_DEFAULT_TIMEOUT_MS, and the 10-minute wait for commands over 10 minutes

Frequently asked questions

What is Claude Code headless mode?

It's Claude Code run non-interactively with claude -p: you pass a prompt, Claude Code runs it with its normal tools and agent loop, prints the result and exits. Scripts, cron jobs and CI pipelines use it. The same engine is available as Python and TypeScript packages in the Agent SDK.

What is bare mode in Claude Code?

A flag that makes a headless run skip auto-discovery of hooks, skills, plugins, MCP servers, auto memory and CLAUDE.md, so the run behaves the same on every machine. Claude keeps Bash, read and edit tools, and you pass anything else in by flag. Anthropic recommends it for scripts and plans to make it the default for -p.

How do I approve tools in a claude -p run?

List them with the allowedTools flag in permission rule syntax, such as Bash(git diff *), or set a baseline with the permission-mode flag: dontAsk for locked-down CI, acceptEdits for file writes, or auto for classifier review. In Manual mode, calls nothing approves are denied.

How do I get JSON output from Claude Code?

Use the output-format flag with json for one object holding the result, session ID and cost estimate, or stream-json for events as they happen. Add the json-schema flag with a JSON Schema to get data in a fixed shape in the structured_output field, and check that field exists before using it.

How do I limit what a headless run costs?

Set the max-budget-usd flag to stop the run once estimated spend reaches an amount, and max-turns to cap agentic turns. Neither has a default. The budget is checked against a client-side estimate that can differ from your bill, and spend can pass the cap, so leave headroom.

Does bare mode use my Claude subscription?

No. Bare mode never reads your OAuth login or the system keychain. Set ANTHROPIC_API_KEY with a Claude Console key, or supply an apiKeyHelper in the settings you pass in. Bedrock and other cloud providers keep using their own credentials.

Can I continue a headless conversation?

Yes. Run claude -p again with the continue flag to pick up the most recent conversation, or with resume and the session ID from the JSON output to pick up a specific one. With the no-session-persistence flag the session isn't saved and can't be resumed.

Give the script rules to follow

A headless run repeats whatever it was told, on every call, with nobody reading along. Bare mode leaves out CLAUDE.md, so the rules the job needs travel with it, in the appended system prompt or a file you pass in. Writing those rules once, and adding one every time a run goes wrong, is the method in our guide to compound engineering for Claude Code. For the other ways to run Claude Code without you, start with our Claude Code automation guide.

#claude-code#Automation#ai-agents#Headless#CI
Free assessment

Stop guessing. Score your first workflow.

Score one workflow in about five minutes. Nine questions, a grade, and the specific gap holding it back - no call required.