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.
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:
claude -p "Explain what this file does" --file src/index.ts
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, 90% of CI/CD use cases rely on this single flag.
| Command | Description | Example |
|---|---|---|
claude -p "prompt" | Basic one-shot execution | claude -p "Summarize this code" |
claude -p "prompt" --file f | Prompt with input file | claude -p "Review this file" --file app.ts |
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 |
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 v1.0.33+ 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:
{
"type": "result",
"result": "Your response here",
"cost_usd": 0.042,
"duration_ms": 3200,
"num_turns": 1
}
The cost_usd field displays the cost in dollars for the call. The duration_ms field indicates the total duration in milliseconds. In practice, a simple call costs between $0.01 and $0.15 depending on the context size.
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. more than 60% of teams using Claude Code in CI integrate it via GitHub Actions. 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 average duration of a code review by Claude Code is 15 to 45 seconds depending on the diff size.
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 --session-id and --resume flags to maintain continuity between calls.
# First call: start a session
claude -p "Analyze the project architecture" \
--output-format json \
--session-id "ci-review-42" > step1.json
# Second call: continue in the same session
claude -p "Now propose improvements" \
--resume --session-id "ci-review-42" \
--output-format json > step2.json
The --session-id is an arbitrary identifier that you choose. The --resume flag tells Claude Code to load the context of the existing session. Each session retains up to 200,000 tokens of context (approximately 150,000 words).
| Flag | Role | Required |
|---|---|---|
--session-id "id" | Name the session | Yes, for multi-turn |
--resume | Resume a session | Yes, from the 2nd call onward |
--max-turns N | Limit internal iterations | No (default: unlimited) |
--continue | Resume the last session | No |
In practice, multi-turn sessions consume 30 to 50% more tokens compared to 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: name your sessions with --session-id and resume them 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 in 2026.
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 covers on average 72% of untested code branches. 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 reduces lint error resolution time by 85% on average. 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 average cost of a CI execution with Claude Code is $0.03 to $0.20 per run. On a project with 50 PRs per week, the monthly budget ranges between $6 and $40.
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) |
CLAUDE_CODE_MAX_TURNS | Default turn limit | Unlimited |
CLAUDE_CODE_MODEL | Claude model to use | claude-sonnet-4-6 |
CLAUDE_CODE_OUTPUT_FORMAT | Default output format | text |
CLAUDE_CODE_VERBOSE | Enable detailed logs | false |
CLAUDE_CODE_CONFIG_DIR | Configuration directory | ~/.claude |
Set these variables in your CI file to avoid repeating flags:
export ANTHROPIC_API_KEY="sk-ant-..."
export CLAUDE_CODE_MAX_TURNS=5
export CLAUDE_CODE_OUTPUT_FORMAT=json
claude -p "Analyze this project"
With Node.js 22 LTS and Claude Code v1.0.33+, headless mode performance reaches an average startup time of 800 ms. Memory consumption stays under 256 MB for most executions.
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 3 most frequent errors in CI are: invalid API key (42% of cases), exceeding --max-turns (28%), and network timeout (18%). Concretely, a timeout occurs after 120 seconds by default.
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.
Claude Code Training
Master Claude Code with our expert instructors. Practical, hands-on training directly applicable to your projects.
View program