Claude Code in headless mode: scripts, cron and CI
Run Claude Code without the interface using claude -p: pipe input, get JSON, pre-approve tools safely, resume sessions, and wire it into cron or CI.
Headless mode is claude -p "your prompt": Claude Code runs one task without the interactive interface, prints the result and exits. That makes it a normal command-line tool you can pipe, put in a script, run from cron or call in CI. Anthropic now documents it as the CLI face of the Agent SDK, but the flag you type is still -p (short for --print).
#How do you run Claude Code non-interactively?
claude -p "What does the auth module do?"
Claude Code prints the answer and exits with code 0 on success and non-zero when the run fails, so a script can branch on it. Failures inside the run, such as missing authentication, are printed as the result on stdout.
Input can come from a pipe, which is the most useful trick:
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
git diff main | claude -p "list typos in this diff, one per line as file:line"
Piped input is capped at 10 MB. For anything larger, write it to a file and refer to the path in the prompt. A bonus of piping a diff: Claude does not need Bash permission to read it.
#Which output format should you use?
--output-format takes three values:
| Value | You get |
|---|---|
text (default) | Plain text |
json | One JSON object with the result, session ID, usage and cost |
stream-json | Newline-delimited JSON events as they happen |
claude -p "Summarize this project" --output-format json | jq -r '.result'
For machine-readable answers, add --json-schema with a JSON Schema. The validated output lands in the structured_output field:
claude -p "Extract the main function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
| jq '.structured_output'
If a run ends without valid structured output (Claude declined, say), that field is simply absent, so check for it before using it. For live tokens, use --output-format stream-json --verbose --include-partial-messages. The JSON result also reports total_cost_usd, a client-side estimate that can differ from your bill; what your usage would cost at API prices explains how to read such figures.
#How do you let it use tools without a human?
Nobody can click "allow" in a script, so decide up front. There are two levers.
Allow specific tools with --allowedTools, using permission-rule syntax:
claude -p "Look at my staged changes and create an appropriate commit" \
--allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"
The space before * matters: Bash(git diff *) matches any command starting with git diff, while Bash(git diff*) would also match git diff-index. Prefer narrow rules like these over a bare Bash.
Set a baseline with --permission-mode: acceptEdits lets file edits through, dontAsk denies anything that would prompt (good for locked-down CI), and auto has a classifier review actions. The permission modes explained article covers the differences. Avoid --dangerously-skip-permissions outside a sandbox with no network.
For jobs where nobody is around, --permission-prompts none makes anything that would prompt get denied automatically, and Claude is told not to retry it. Add --max-budget-usd to cap what a run may spend, and for tighter control a hook can refuse specific commands.
#How do you continue a conversation?
claude -p "Review this codebase for performance issues"
claude -p "Now focus on the database queries" --continue
# or keep the ID to resume exactly that session
sid=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$sid"
Sessions are saved like any other, so you can open them later in a normal terminal with claude --resume. If you do not want the run saved, --no-session-persistence turns it off.
#What changes in CI and cron?
Three things to decide.
What the run loads. Without --bare, claude -p discovers hooks, skills, plugins, MCP servers, auto memory and CLAUDE.md the way an interactive session does, including the project's .claude/settings.json and .mcp.json, with no trust dialog and no per-server approval. That is convenient on your laptop and surprising on a build machine. --bare skips all of it for a consistent run; you then pass what you need with --append-system-prompt, --settings, --mcp-config, --agents or --plugin-dir. Bare mode never reads your login: it needs ANTHROPIC_API_KEY or an apiKeyHelper. Mind that hooks passed through --settings still do not run in bare mode.
How it authenticates. An unattended machine cannot do a browser login. claude setup-token creates a long-lived token for a Claude subscription; check the Claude Code docs for where the CI job reads it. Remember that subscription use counts toward your plan's limits: see Claude Code usage limits.
How it ends. If you stop a run with SIGTERM, Claude Code exits with code 143 and leaves the turn unfinished. Send SIGINT first if you want the turn to end cleanly. After the main turn, a run can also wait up to ten minutes for background work it started, such as background subagents.
A minimal cron entry that writes a daily summary:
# crontab -e
0 8 * * 1-5 cd ~/code/app && git log --since=yesterday --oneline | claude -p "summarize these commits for a standup, 5 bullets max" --allowedTools "Read" >> ~/standup.md
For repositories on GitHub or GitLab, Anthropic publishes ready-made integrations (GitHub Actions and GitLab CI/CD) built on the same -p interface, so you rarely have to write the workflow file from scratch. For recurring work that should live outside your machine, see scheduled Claude Code routines.
#What can't you do in headless mode?
Terminal-only commands such as /login are unavailable. Your own skills and slash commands work if you put /skill-name in the prompt. A few built-ins accept an argument, for example /model sonnet. Nobody is there to answer a question, so tasks that need your judgment in the middle belong in an interactive session, not in -p.
#In Relais
Relais is a desktop app, not a CI tool, so it does not replace a script on a build server. Where it overlaps is the repeating part: its "Repeat" feature resends a prompt at set times, in the same session or a fresh one each time, and sessions it runs are normal Claude Code sessions in ~/.claude/projects, so claude --resume opens them. More on the features page.