TL;DR
This cheatsheet gathers all the commands for using Claude Code in headless mode within your CI/CD pipelines. Find the `-p` flag syntax, output formats, GitHub Actions integrations, and programmatic multi-turn sessions. Keep this practical sheet handy to automate your workflows without human intervention.
This cheatsheet gathers all the commands for using Claude Code in headless mode within your CI/CD pipelines. Find the -p flag syntax, output formats, GitHub Actions integrations, and programmatic multi-turn sessions. Keep this practical sheet handy to automate your workflows without human intervention.
Claude Code's headless mode is the ability to run the tool as a non-interactive command line, without a conversational interface, to integrate it into scripts and automation pipelines. This feature transforms Claude Code into an automation building block for CI/CD, AI linting, and automated code review.
SFEIR Institute trainings
Claude Code Training
1 day · Fundamentals
AI-Augmented Developer
2 days · Intermediate
How to launch Claude Code in headless mode with the -p flag?
The -p flag (for print) is the entry point to headless mode. It allows you to send a single prompt to Claude Code and retrieve the response on standard output, without opening the interactive interface. Run this command for a first test:
cat src/index.ts | claude -p "Explain what this file does"
Claude Code processes the prompt, generates the response, and exits immediately. The exit code reflects success (0) or failure (1) of the execution. In practice, most CI/CD use cases rely on this single flag.
| Command | Description | Example | ||
|---|---|---|---|---|
claude -p "prompt" | Basic one-shot execution | claude -p "Summarize this code" | ||
| `cat f \ | claude -p "prompt"` | Prompt with file via stdin | `cat app.ts \ | claude -p "Review this file"` |
claude -p "prompt" --output-format json | Output in JSON format | claude -p "List the bugs" --output-format json | ||
claude -p "prompt" --output-format stream-json | Streaming JSON output | claude -p "Analyze" --output-format stream-json | ||
claude -p "prompt" --max-turns 3 | Limit execution turns | claude -p "Fix" --max-turns 3 | ||
claude -p "prompt" --allowedTools | Restrict allowed tools | claude -p "Lint" --allowedTools "Read,Write" | ||
claude -p "prompt" --model | Choose the Claude model | claude -p "Test" --model claude-sonnet-4-6 | ||
claude -p "prompt" --verbose | Enable detailed logs | claude -p "Debug" --verbose | ||
claude -p "prompt" --bare | Skip hooks, skills, MCP, and memory | claude -p "Test" --bare | ||
claude -p "prompt" --max-budget-usd | Cap spending per execution | claude -p "Review" --max-budget-usd 0.50 |
To discover each option in detail, check out the complete headless mode command reference which covers all available flags.
Key takeaway: the -p flag turns Claude Code into a standard CLI tool compatible with any automation pipeline.
What output formats are available for parsing?
Claude Code offers three output formats via --output-format. Choose the format suited to your use case to parse the response efficiently.
text format (default)
claude -p "Explain this function" --output-format text
The text format returns the raw response in plain text. Use it for simple cases where you redirect the output to a file or display it in CI logs.
json format
claude -p "Analyze this code" --output-format json
The JSON output is a single object containing the complete result. Here is the typical structure:
{
"result": "Your response here",
"session_id": "...",
"total_cost_usd": 0.042
}
The total_cost_usd field displays the cost in dollars for the call, and the payload also includes a per-model cost breakdown. The cost of a call depends on the model and the number of tokens processed, so it varies with the size of your context.
stream-json format
claude -p "Review this PR" --output-format stream-json | jq '.type'
The stream-json format emits JSON objects line by line (NDJSON). Each event has a distinct type field. This format allows you to process the response in real time without waiting for the execution to complete.
| Format | Use case | Parsing | Perceived latency |
|---|---|---|---|
text | CI logs, terminal display | No parsing required | End of execution |
json | Scripts, API integrations | jq, Python json.loads() | End of execution |
stream-json | Dashboards, real-time feedback | NDJSON line by line | Immediate |
To master output handling in your scripts, the context management cheatsheet gives you reusable parsing patterns.
Key takeaway: use json for automated scripts and stream-json for real-time feedback.
How to integrate Claude Code into GitHub Actions?
The GitHub Actions integration relies on a YAML workflow that installs Claude Code then runs it with -p. Create a .github/workflows/claude-review.yml file:
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Run review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude -p "Review the changes in this PR and list potential issues" \
--output-format json > review.json
The ANTHROPIC_API_KEY secret is the Anthropic API key stored in GitHub secrets. Configure it in Settings > Secrets > Actions of your repository. The duration of a code review varies with the size of the diff and the model used.
To secure tool permissions in CI, check out the permissions and security cheatsheet which details the --allowedTools mode.
Key takeaway: store your API key in GitHub secrets and limit allowed tools with --allowedTools in CI.
How to manage programmatic multi-turn sessions?
A multi-turn session allows you to chain multiple prompts within the same conversational context. Use the --resume flag to maintain continuity between calls.
# First call: start a session
RESULT=$(claude -p "Analyze the project architecture" \
--output-format json)
echo "$RESULT" > step1.json
SESSION=$(echo "$RESULT" | jq -r '.session_id')
# Second call: continue in the same session
claude -p "Now propose improvements" \
--resume "$SESSION" \
--output-format json > step2.json
The --resume flag followed by a session identifier tells Claude Code to load the context of the existing session. The --continue flag (without argument) resumes the last session. The amount of context a session can hold depends on the context window of the underlying Claude model rather than a fixed per-session limit.
| Flag | Role | Required |
|---|---|---|
--resume SESSION_ID | Resume a specific session | Yes, from the 2nd call |
--continue | Resume the last session | No |
--max-turns N | Limit internal iterations | No (default: unlimited) |
In practice, multi-turn sessions accumulate context across calls and therefore consume more tokens than isolated calls. Limit the number of turns with --max-turns to control costs.
To structure your programmatic conversations, the first conversations cheatsheet explains the fundamental conversational patterns that you will find again in headless mode.
Key takeaway: retrieve the session_id from the JSON response and resume your sessions with --resume for multi-step workflows.
What are the advanced CI/CD use cases?
Claude Code's headless mode covers scenarios well beyond simple code review. Here are concretely the most common use cases.
Automatic test generation
claude -p "Generate unit tests for src/auth.ts with vitest" \
--allowedTools "Read,Write" \
--max-turns 5 \
--output-format json
Adding AI-generated tests helps cover code branches that were previously untested. Limit tools to Read,Write to prevent uncontrolled command execution.
Automatic linting and fixing
claude -p "Fix ESLint errors in src/ without changing the logic" \
--allowedTools "Read,Write" \
--output-format text
An automatic fix pipeline can significantly reduce the time spent resolving lint errors. Always verify the generated diff before auto-merging.
Automatic documentation
claude -p "Generate JSDoc for all exported functions in lib/" \
--allowedTools "Read,Write" \
--max-turns 10
To explore more concrete pipeline examples, the headless mode examples page offers ready-to-use workflows.
The complete headless mode and CI/CD guide details each scenario with complete pipeline architectures.
Key takeaway: always restrict allowed tools (--allowedTools) in CI to limit the AI's scope of action.
How to secure Claude Code execution in CI/CD?
Security in CI/CD requires restricting Claude Code's capabilities. Apply these 5 rules systematically.
- Limit tools with
--allowedTools "Read,Write": never useBashin automated CI - Store the API key in a secret manager (GitHub Secrets, Vault, AWS SSM)
- Set
--max-turnsto a reasonable value (3 to 10) to prevent infinite loops - Validate JSON output with a schema before acting on the result
- Audit each execution by keeping logs (
--verbose > claude-audit.log)
claude -p "Review this code" \
--allowedTools "Read" \
--max-turns 3 \
--verbose \
--output-format json 2>claude-audit.log
The cost of a CI execution with Claude Code depends on the model, the number of tokens processed, and the number of turns, so plan your budget from your own observed runs rather than a fixed figure.
To understand the permissions model in depth, the permissions and security cheatsheet guides you step by step. Also consider checking the common headless mode errors to anticipate frequent pitfalls.
Key takeaway: the trio --allowedTools, --max-turns, and --verbose is the minimum security foundation in CI.
What shortcuts and environment variables should you know?
In headless mode, keyboard shortcuts do not exist (no interactive interface). However, several environment variables control Claude Code's behavior in CI.
| Variable | Role | Default value |
|---|---|---|
ANTHROPIC_API_KEY | Anthropic API key | None (required) |
Set the API key in your CI file and use command-line flags for other options:
export ANTHROPIC_API_KEY="sk-ant-..."
claude -p "Analyze this project" --max-turns 5 --output-format json
Keep your Claude Code installation up to date for the best headless mode performance. Note that the npm-installed claude binary is native and does not invoke Node at runtime.
The installation and first launch cheatsheet details the initial configuration needed before using headless mode. You will also find in the slash commands cheatsheet useful commands for configuring Claude Code before automating it.
Key takeaway: configure environment variables once in your CI to simplify all your headless calls.
How to debug a failing Claude Code pipeline?
When a pipeline fails, follow this 4-step diagnostic procedure.
- Check the exit code:
echo $?after the call (0 = success, 1 = error) - Enable
--verboseto get detailed logs on stderr - Inspect the JSON output: the
errorfield contains the error message - Test locally with the same prompt before relaunching the pipeline
# Full diagnostic
claude -p "My prompt" \
--output-format json \
--verbose 2>debug.log
# Check the exit code
echo "Exit code: $?"
# Read the logs
cat debug.log
The most frequent error categories in CI are an invalid or missing API key, exceeding the --max-turns limit, and network timeouts.
For an exhaustive list of error messages and their solutions, check out the common headless mode errors guide. The Git integration cheatsheet also helps you resolve problems related to Git operations in your pipelines.
Key takeaway: --verbose and the exit code are your two first debugging reflexes in CI.
Should you take a training course to master Claude Code in CI/CD?
Automating Claude Code in CI/CD requires understanding flags, output formats, sessions, and security best practices. SFEIR Institute offers structured training courses to accelerate this skill-building.
The Claude Code one-day training has you practice headless mode on concrete labs: you build a complete GitHub Actions pipeline and configure security permissions end to end.
To go further, the AI-Augmented Developer 2-day training covers all AI tools for developers, including advanced CI/CD integration with multi-turn sessions and JSON parsing.
Experienced developers can take the AI-Augmented Developer - Advanced one-day module, focused on complex pipeline architectures and API cost optimization in production.
Key takeaway: SFEIR Institute trainings combine theory and hands-on labs to make you operational with Claude Code in CI/CD from day one.
Recent articles about Claude

Claude Managed Agents: Anthropic's Platform for Production Agent Deployment
Anthropic launches Managed Agents: a cloud platform for deploying AI agents in production. Secure sandbox, checkpointing, multi-agent, autonomous sessions lasting hours. Notion, Rakuten, Asana and Sentry already use it.

Claude Code Dream & Auto Dream: Automatic Memory Consolidation
After 20 sessions, Auto Memory notes become a mess. Auto Dream solves this by automatically consolidating Claude Code's memory: deduplication, stale entry removal, relative-to-absolute date conversion.

Claude Code Auto Mode: Autonomy Without the Risk
Auto Mode in Claude Code eliminates permission interruptions while keeping a safety net. A classifier analyzes every action before execution and blocks destructive operations. The sweet spot between approving everything and letting everything through.
Claude Code Training
Master Claude Code fundamentals in 1 day with our expert instructors. 60% hands-on practice on real-world cases.
Discover the training