How to Run Claude Code Headless for CI/CD Pipelines
To run Claude Code headless for CI/CD pipelines, pass the -p (or --print) flag with a prompt string on the command line. Claude executes the task, writes its response to standard output—either as plain text or as structured JSON—and exits with a status code your script can check. Because there is no interactive session, you must explicitly grant tool permissions upfront so the process never hangs waiting for a confirmation that will never come.
What Is Claude Code Headless Mode?
Headless mode is a way to run Claude Code without any interactive terminal UI, so it can be driven entirely by scripts, automation tools, and CI/CD pipelines. Instead of opening a chat-style session, you supply a prompt directly on the command line, and Claude writes its answer to stdout before exiting. This makes it trivially composable with shell pipes, jq, GitHub Actions steps, cron jobs, and any other tool that reads from standard streams.
Headless mode is also the foundation of the Claude Agent SDK, which wraps the same execution engine in Python and TypeScript objects so you can embed autonomous coding agents directly in applications, orchestrate multiple agents in parallel, and parse structured output without shelling out manually.
How Do You Set Up Claude Code for Headless Use?
- Install Claude Code globally with
npm install -g @anthropic-ai/claude-code. - Authenticate with your Anthropic account or API key. Run
claudeinteractively the first time if needed to complete authentication. - Run a headless command by passing the
-pflag followed by your prompt:claude -p "Your prompt here". - Add
--output-format json(or--output-format stream-json) if you need machine-readable output for scripting. - Add
--allowedToolsto specify which tools Claude may use (for example,Read,Edit,Bash) and--permission-mode dontAskto suppress all interactive permission prompts. - Optionally add
--cwd /path/to/projectto set the working directory Claude operates in. - For multi-turn workflows, capture the
session_idfrom JSON output and pass it via--resume <session_id>in the next call.
For full CLI option details, see the Claude Code CLI reference.
How Do You Avoid the Most Common Headless Pitfall—Hanging Processes?
The single most disruptive mistake in headless CI/CD use is a process that hangs indefinitely. This happens when Claude needs permission to use a tool but has no terminal to ask. The fix is straightforward: always add --permission-mode dontAsk in headless and CI contexts, and use --allowedTools to enumerate exactly which tools Claude may invoke without asking.
Use narrow, explicit tool patterns such as
Bash(npm test *)rather than broad shell wildcards. When--permission-mode autois active, Claude Code automatically removes rules that would grant blanket shell access or wildcarded script interpreters to reduce autonomous execution risk.
Also note that slash commands such as /review are interactive-UI features and silently fail in headless mode. Write your intent as a natural-language prompt instead: claude -p "Review this code for security issues and style problems."
What Does a Real CI/CD Headless Command Look Like?
Example 1: Summarize Git Commits (Beginner)
Pipe git log output directly into Claude to generate release notes without opening a chat interface:
git log --oneline -20 | claude -p "Summarize these commits into bullet-point release notes grouped by feature, fix, and chore."
Claude prints plain-text release notes to stdout. This is the simplest headless pattern—stdin piping with no extra flags—and replaces manual copy-paste from a terminal into a chat window.
Example 2: Automated Build-Error Report Saved as JSON (Intermediate)
A CI script captures build output, sends it to Claude, and saves a structured JSON report so a downstream step can parse the root cause and suggested fix without human involvement:
#!/bin/bash
BUILD_LOG=$(npm run build 2>&1 || true)
echo "$BUILD_LOG" | claude -p "Analyze this build output. Return: 1) root cause in one sentence, 2) list of affected files, 3) exact command or code fix." --output-format json > build-report.json
cat build-report.json
The JSON output format makes Claude's response machine-parseable, so downstream CI steps can branch on the result, post it to Slack, or open a ticket automatically.
What Are the Best Real-World Use Cases for Headless Claude in CI/CD?
- CI/CD pipeline code review: A GitHub Actions workflow runs on every pull request, pipes the PR diff into Claude with a security-focused prompt, and posts the JSON result as a PR comment—giving reviewers an automated first-pass analysis before any human looks at the code.
- Automated build-error diagnosis: A build script captures stderr from a failing compile or test run, then pipes it to Claude asking for root cause, affected files, and the exact fix. The result is saved to a report file engineers check after the pipeline fails.
- GitHub issue auto-labeling: A webhook fires whenever a new issue is opened. A small server pipes the issue body to Claude in headless mode and asks it to recommend labels, then calls the GitHub API to apply them automatically.
- Scheduled codebase health checks: A nightly cron job runs Claude in headless mode against the main branch, asking it to flag stale TODOs, outdated dependency comments, and misleading variable names. Results are written to a Markdown file and committed back to a maintenance branch.
- Parallel multi-agent PR review: Three Claude instances are launched concurrently via the Agent SDK—one focused on logic correctness, one on security vulnerabilities, and one on performance. Their JSON outputs are aggregated into a single structured report.
- Pre-commit hook linting extension: A git pre-commit hook pipes the staged diff to Claude and asks it to flag issues beyond what ESLint or Prettier catch—things like misleading function names or logic that doesn't match the commit message.
When Should You Use Headless Mode vs. the Agent SDK vs. the Raw API?
| Scenario | Best Choice | Why |
|---|---|---|
| Quick CI hook, shell script, or cron job | Headless mode (claude -p) |
No application code needed; composable with any shell tooling |
| Application embedding Claude as a component | Claude Agent SDK | Parse streaming events programmatically, manage multiple agent lifecycles, run parallel agents with fine-grained control |
| Active collaboration, exploring a codebase | Interactive Claude Code (no -p flag) |
Human judgment mid-task adds value; review and approve tool calls in real time |
| Non-coding product, maximum model control | Direct Anthropic Messages API | Full control over system prompts and token budgets without the built-in tool suite |
| Single structured response after task completes | --output-format json |
Clean, parseable output with no intermediate events |
| React to intermediate reasoning or tool calls in real time | --output-format stream-json |
Enables orchestrators to dispatch sub-tasks as Claude identifies them |
What Other Pitfalls Should You Watch For?
- Lost session context between invocations: Headless mode is stateless by default. Capture the
session_idfield from the JSON output of the first call and pass it via--resume <session_id>in subsequent calls to restore context. - Large inputs silently truncated: Piped stdin has a size cap; exceeding it exits with a non-zero status and an error message. For large log files or diffs, either truncate before piping (for example with
tail -n 1000), or save the content to a file and use--allowedTools Readwith--cwdso Claude reads it directly. - Hidden errors with stream-json: When using
--output-format stream-jsonwithout--verbose, a failed run may exit with a non-zero status code and print nothing to stderr, making pipeline debugging very difficult. Add--verbosein development and staging pipelines; strip it in production only after confirming stable behavior. - Broad permission wildcards silently dropped: When
--permission-mode autois active, Claude Code drops permission rules that would grant arbitrary code execution. Audit your allowed-tools list and use narrow, explicit patterns.
Is Headless Mode Worth Adding to Your CI/CD Pipeline?
For teams that already use Claude Code interactively, headless mode is a zero-friction extension of the same tool into automation. You get file-system access, shell execution, and all of Claude's built-in tools without setting up any additional infrastructure. The JSON output format makes it straightforward to wire Claude's analysis into existing pipeline steps, Slack notifications, or issue trackers.
The main investment is getting permissions right upfront—using --allowedTools with explicit, narrow patterns and --permission-mode dontAsk—so your pipelines never hang. Once that's in place, headless Claude becomes a reliable, scriptable component you can drop into any workflow that benefits from language-model reasoning over code, logs, or text.
For deeper programmatic control or parallel agent orchestration, the headless mode documentation covers the transition path to the Agent SDK, which wraps the same execution engine in Python and TypeScript for application-level embedding.
Frequently asked questions
What flag do I use to run Claude Code headless?
Pass the -p (or --print) flag followed by your prompt string. Claude executes the task, writes its response to standard output, and exits with a status code your script can check.
Why does my headless Claude process hang in CI?
The process is waiting for a permission confirmation it will never receive because there is no interactive terminal. Add --permission-mode dontAsk and use --allowedTools to enumerate exactly which tools Claude may invoke without asking.
How do I get machine-readable output from headless Claude?
Add --output-format json to get a single structured JSON response after the task completes, or --output-format stream-json to receive intermediate events in real time as Claude works.
Can headless Claude maintain context across multiple pipeline steps?
Headless mode is stateless by default between separate invocations. Capture the session_id from the JSON output of the first call and pass it via --resume <session_id> in subsequent calls to restore context.
What is the difference between headless mode and the Claude Agent SDK?
Headless mode (claude -p) is best for quick, script-driven tasks without writing application code. The Agent SDK wraps the same execution engine in Python and TypeScript for embedding Claude in applications, parsing streaming events programmatically, and running parallel agents with fine-grained control.
Do slash commands like /review work in headless mode?
No. Slash commands are interactive-UI features and silently fail in headless mode. Write your intent as a natural-language prompt instead, for example: claude -p "Review this code for security issues and style problems."
Headless mode is one of 85 features in Claude Master — the independent, always-current manual with worked examples, the pitfalls, and the workflows that make Claude pay.
Get Claude Master — founding price →Independent product. Not affiliated with or endorsed by Anthropic. "Claude" is a trademark of Anthropic, used here only to describe the subject of this guide.