Claude Code headless mode is the non-interactive way to run Claude Code: you pass a prompt with claude -p, it does the work, prints the answer and exits. No chat window, no approval clicks, so it fits into Bash scripts, cron jobs and CI/CD pipelines like any other command-line tool.
That changes what the tool is good for. In the terminal chat, Claude Code is a pair programmer. In headless mode it becomes a worker for the dull, repeating jobs: reading overnight logs, checking a config before a deploy.
What does Claude Code headless mode actually do?
You add -p (short for –print) to the claude command. Claude Code reads the prompt, uses whatever tools you allowed, writes the result to standard output and returns control to your script.
claude -p "Explain in two sentences what /etc/fstab is used for."
Anthropic’s docs no longer use “headless” as the main name. The current page is called “Run Claude Code programmatically”, and it treats claude -p as the command-line face of the Claude Agent SDK. The Python and TypeScript SDK packages run the same engine with more control.
Since it reads stdin, you can pipe data in and send the answer to a file:
cat build-error.txt | claude -p "Explain the root cause of this build error in three lines" > output.txt
Two practical details. Exit code 0 means success and anything else means the run failed, so a script can branch on it. Piped input stops at 10 MB; bigger inputs should go into a file that the prompt points to.
Claude Code CLI flags for non-interactive runs
Most scripted jobs need only a few options.
| Flag | What it does in a script |
|---|---|
| -p, –print | Runs Claude Code in non-interactive mode and prints the result |
| –output-format json | Returns one JSON object with the result, session ID, turns and estimated cost |
| –output-format stream-json | Emits one JSON event per line while the run is in progress |
| –json-schema | Makes the answer match a JSON Schema, returned in structured_output |
| –allowedTools | Pre-approves specific tools, for example “Read” or “Bash(git diff *)” |
| –permission-mode | Sets the default for everything else: dontAsk, acceptEdits, auto |
| –max-turns | Limits how many agent steps one run can take |
| –bare | Starts clean, without local hooks, plugins, MCP servers or CLAUDE.md |
| –continue / –resume | Continues the last session, or one picked by session ID |
| –append-system-prompt | Adds your own instructions on top of the defaults |
JSON output is what makes Claude Code automation reliable. A pipeline should never scrape prose. The json format gives you the text in a result field, plus a session_id, num_turns, duration_ms and an estimated total_cost_usd. With jq it takes one line:
claude -p "Summarize this project" --output-format json | jq -r '.result'
If a downstream system expects fixed fields, say a ticket with a title and a severity, pass –json-schema. The answer then lands in structured_output, and you check that the field exists before using it.
Bare mode is the flag people skip and later regret. A normal claude -p run loads whatever the machine has configured: personal hooks in ~/.claude, the project’s MCP servers, memory files. So the same command can behave differently on a developer laptop and on a CI runner. With –bare nothing is auto-loaded. You pass settings, MCP config and extra instructions explicitly, and authenticate with ANTHROPIC_API_KEY instead of a subscription login. Anthropic says bare mode is the recommended setup for scripts and will become the default for -p.
Claude Code automation: five jobs ops teams hand off first
Good candidates share one trait. A person reads a lot of text and writes back a few lines or a yes/no.
Log triage on a Claude Code cron job
On November 17, IT-Connect published a step-by-step example. A Python script takes the last 2,000 lines of the SSH auth log, pipes them into claude -p with a fixed prompt and –output-format json, and prints a ten-line summary of suspicious logins. Cron runs it every morning:
0 7 * * * /usr/bin/python3 /opt/scripts/triage-ssh.py | mail -s "SSH triage" admin@example.com
Claude will not out-detect fail2ban. The gain is that the admin reads ten lines over coffee instead of scrolling two thousand.
Config review before a deploy
Feed an Nginx, Terraform or Kubernetes file into a run that returns findings through a JSON schema, each with a severity. If anything comes back as high, fail the build. Policy-as-code still does the hard checks; this catches the odd mistakes nobody wrote a rule for.
Pull request review with GitHub Actions
Anthropic maintains official integrations for GitHub Actions and GitLab CI/CD. A lighter option is a plain shell step: pipe gh pr diff into claude -p with –append-system-prompt asking for a security review, then post the JSON result as a PR comment.
Weekly change summaries
Point a scheduled run at the merged commits for each service. Managers get a readable change log; release notes come almost for free.
Backup and scheduler report digests
Backup software and job schedulers write reports that stay unread until a restore fails. A nightly run that flags only failures and odd numbers costs little and closes a real gap.
Claude Code permissions: how to run it unattended without the risk
Headless mode removes the person who would normally press “approve”. Set up the guardrails before the first scheduled run, not after.
Pre-approve as little as possible. A log summary needs Read and maybe one grep pattern. It does not need Bash in general. Rules match by prefix, so Bash(git diff *) allows git diff and nothing else. Since Claude Code v2.1.302, a -p run with no mode set starts in Manual mode, and any call that needs approval is simply denied. That default is the right one for most jobs.
Do not reach for bypassPermissions. IT-Connect’s warning is blunt: it gives Claude the full rights of the account running it, so never use it as root on a production server. If a job truly needs wide access, run it as a dedicated low-privilege user, inside a container or on a throwaway VM. For locked-down CI, –permission-mode dontAsk denies everything that is not explicitly allowed. For scheduled jobs, –permission-prompts none tells Claude nobody is there to approve anything, so it moves on instead of hanging.
Assume the input is hostile. This is the risk most teams underestimate. Logs, emails, tickets and web pages can carry planted instructions; a crafted username in an auth log is enough for an attempt. A narrow tool list is the real defence, because a successful prompt injection then has nothing dangerous to call.
Mind what the repository brings. Without –bare, claude -p runs the project’s hooks and connects its MCP servers, with no trust prompt. On a CI runner building an outside contributor’s pull request, that is an open door. Use bare mode there.
Cap the spend. Each call is billed. The JSON output shows an estimated cost per run, and –max-budget-usd stops a run that goes over a limit. A smaller model handles routine summaries fine.
When interactive mode is the better choice
Headless runs suit short tasks with a clear input and a clear expected output. They are a bad fit for open-ended work, where the next step depends on what Claude finds: debugging an unfamiliar outage, or modernizing a legacy system. There you want the interactive session and a human making calls.
Output also varies a little between runs. Anything downstream should read structured fields, never match on wording. If a job needs exact, repeatable logic, put that logic in code and keep Claude for the reading and judgment.
FAQ
What is Claude Code headless mode?
It is Claude Code running without its interactive interface. You call claude -p with a prompt, it prints the result and exits, which lets you use it in scripts, cron jobs and CI/CD pipelines.
Is headless mode the same as the Claude Agent SDK?
Same engine, different entry points. claude -p is the fastest route from a shell script. The Python and TypeScript SDK packages add finer control, such as tool approval callbacks and native message objects.
How do I run Claude Code in a cron job?
Put the claude -p call in a script, ask for –output-format json, limit tools with –allowedTools, then schedule the script in crontab like any other job.
How do I get JSON output from Claude Code?
Add –output-format json and read the result field. For fixed fields, add –json-schema and read structured_output.
Is it safe to run Claude Code unattended?
Yes, with guardrails: a short –allowedTools list, a low-privilege account or container, –bare in CI, and the assumption that input may contain prompt injection. Avoid bypassPermissions on production systems.
Does Claude Code work with GitHub Actions?
Yes. Anthropic offers official GitHub Actions and GitLab CI/CD integrations, and claude -p also runs from any CI shell step.
