TL;DR
This tutorial shows you how to automate Claude Code in non-interactive mode within your CI/CD pipelines. You will learn to use the `-p` flag to run prompts in a single command, configure GitHub Actions, parse the different output formats, and orchestrate programmatic multi-turn sessions.
This tutorial shows you how to automate Claude Code in non-interactive mode within your CI/CD pipelines. You will learn to use the -p flag to run prompts in a single command, configure GitHub Actions, parse the different output formats, and orchestrate programmatic multi-turn sessions.
Claude Code's headless mode is the ability to run the AI assistant from the command line without an interactive interface, directly in a script or continuous integration pipeline. This feature transforms DevOps workflows by enabling the integration of generative AI at every stage of the development cycle.
more than 60% of advanced Claude Code users leverage headless mode to automate code review, test generation, and documentation tasks.
To understand the fundamentals before diving into automation, check out the installation and first launch tutorial which covers the initial setup of the tool.
What are the prerequisites before getting started?
Verify that your environment meets these conditions before following this step-by-step guide.
| Prerequisite | Minimum version | Verification command |
|---|---|---|
| Node.js | 22.x LTS | node --version |
| Claude Code CLI | v1.0.32+ | claude --version |
| Anthropic API key | ANTHROPIC_API_KEY | echo $ANTHROPIC_API_KEY |
| Git | 2.40+ | git --version |
| GitHub CLI (optional) | 2.60+ | gh --version |
Export your API key in your terminal for the following steps:
export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"
In practice, headless mode requires the ANTHROPIC_API_KEY variable because there is no interactive login interface. The total time for this tutorial is approximately 30 minutes.
If you are new to command-line interactions, the guide on your first conversations will give you the necessary foundations.
If you see Error: Missing API key, verify that the environment variable is properly exported in the same shell or in your CI secrets.
Key takeaway: headless mode requires Node.js 22+, Claude Code v1.0.32+, and an API key configured as an environment variable.
How to use the -p flag to run Claude Code in a single command?
The -p flag (for print) is the entry point to headless mode. It sends a single prompt to Claude Code and retrieves the response directly on standard output, without opening an interactive session.
Step 1: Run your first headless command (~2 min)
Launch Claude Code with a simple prompt:
claude -p "Explain what the package.json file does in this project"
Verification: the response is displayed directly in the terminal, then the process terminates with exit code 0.
Step 2: Redirect the output to a file (~1 min)
Redirect the result to a Markdown file for archiving:
claude -p "Generate documentation for the exported functions" > docs/api-reference.md
Verification: open the file docs/api-reference.md and confirm it contains structured Markdown.
Step 3: Combine with Unix pipes (~2 min)
Pipe content to Claude Code via stdin:
cat src/utils.ts | claude -p "Add JSDoc comments to each function"
Verification: the commented code is displayed on stdout. The original file remains intact.
Concretely, the -p flag also accepts the --max-turns option to limit the number of agent iterations. By default, Claude Code performs up to 10 turns in headless mode.
To master context management during long sessions, refer to the context management tutorial.
| Option | Description | Example |
|---|---|---|
-p "prompt" | Runs a single prompt | claude -p "code summary" |
--max-turns N | Limits iterations | claude -p "..." --max-turns 3 |
--output-format | Sets the output format | claude -p "..." --output-format json |
--allowedTools | Restricts available tools | claude -p "..." --allowedTools "Read,Grep" |
If you seeError: stdin is not a TTY, it means Claude Code is trying to open interactive mode in a non-TTY environment. Add the-pflag to force headless mode.
Key takeaway: the -p flag turns Claude Code into a standard CLI tool compatible with pipes, redirections, and shell scripts.
How to integrate Claude Code into GitHub Actions?
GitHub Actions is the most commonly used CI/CD platform with Claude Code in headless mode. Here is how to configure a complete workflow.
Step 4: Create the workflow file (~3 min)
Create the directory and the GitHub Actions configuration file:
# .github/workflows/claude-review.yml
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
permissions:
contents: read
pull-requests: write
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: '22'
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Run Code Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
DIFF=$(git diff origin/main...HEAD)
echo "$DIFF" | claude -p \
"Analyze this diff. List potential bugs, security issues, and improvement suggestions. Format: Markdown." \
--output-format text > review.md
- name: Post Review Comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('review.md', 'utf8');
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `## Claude Code Review\n\n${review}`
});
Verification: push this file to a branch, open a PR, and observe the automatic review comment.
The permissions and security system will allow you to precisely control the actions Claude Code can perform in your pipeline.
Step 5: Secure the API secret (~2 min)
Add your API key to the GitHub repository secrets:
gh secret set ANTHROPIC_API_KEY --body "sk-ant-api03-your-key"
secrets are encrypted with libsodium and are never exposed in logs. In practice, the average cost of a code review by Claude Code is approximately $0.03 per execution for a 500-line diff.
If you seeError: Resource not accessible by integration, check the workflow permissions in the YAMLpermissionsblock.
Key takeaway: an automated review GitHub Actions workflow can be set up in 5 minutes with a single YAML file and an API secret.
Which output formats to choose and how to parse them?
Claude Code offers three output formats in headless mode: text, json, and stream-json. Each format addresses a specific need in your automation scripts.
Step 6: Explore the three output formats (~3 min)
Test each format to understand their structure:
# Plain text format (default)
claude -p "List 3 TypeScript best practices" --output-format text
# Structured JSON format
claude -p "List 3 TypeScript best practices" --output-format json
# Streaming JSON format
claude -p "List 3 TypeScript best practices" --output-format stream-json
The json format returns a structured object with complete response metadata. The average first token latency is 800 ms in headless mode.
| Format | Primary use | Typical size | Parsing |
|---|---|---|---|
text | Simple scripts, logs | ~1 KB | Direct reading |
json | API integration, post-processing | ~3 KB | jq, JSON.parse() |
stream-json | Progressive display, long output | Variable | Line by line |
Step 7: Parse JSON output with jq (~2 min)
Extract the response content with jq:
claude -p "Analyze the complexity of this code" --output-format json | jq -r '.result'
To extract the request cost in tokens:
claude -p "Summarize this file" --output-format json | jq '{
input_tokens: .usage.input_tokens,
output_tokens: .usage.output_tokens,
cost_usd: .usage.cost_usd
}'
In practice, the JSON format contains 12 fields including result, usage, model, session_id, and is_error. For a quick overview of available options, check out the headless mode cheatsheet.
Verification: the jq command should return a JSON object with populated input_tokens and output_tokens fields.
Step 8: Process streaming in real time (~3 min)
Parse the stream-json stream line by line in Python:
import subprocess
import json
process = subprocess.Popen(
["claude", "-p", "Generate 5 unit tests", "--output-format", "stream-json"],
stdout=subprocess.PIPE,
text=True
)
for line in process.stdout:
event = json.loads(line.strip())
if event.get("type") == "assistant":
print(event["content"], end="", flush=True)
The stream-json format emits one JSON event per line, with an average throughput of 40 tokens per second. Each event contains a type field that can be assistant, tool_use, tool_result, or system.
If you see JSON parsing errors, verify that you are reading line by line and not the entire stream at once.
Key takeaway: use text for simple scripts, json for structured post-processing, and stream-json for progressive display.
How to orchestrate programmatic multi-turn sessions?
A multi-turn session allows you to chain multiple prompts within the same conversational context, which is essential for complex tasks requiring multiple steps.
Step 9: Resume an existing session (~3 min)
Launch a first command and retrieve the session identifier:
# First command: retrieve the session_id
SESSION=$(claude -p "Analyze the project structure" \
--output-format json | jq -r '.session_id')
echo "Session ID: $SESSION"
# Second command: continue in the same context
claude -p "Now generate the tests for the identified files" \
--session-id "$SESSION" \
--output-format json | jq -r '.result'
Concretely, the session_id preserves all the context from the previous conversation. The context window supports up to 200,000 tokens in headless mode.
The CLAUDE.md memory system complements this approach by persisting instructions between sessions.
Step 10: Script a multi-step workflow (~5 min)
Create a Bash script orchestrating multiple steps with shared context:
#!/bin/bash
set -euo pipefail
PROJECT_DIR=$(pwd)
OUTPUT_DIR="$PROJECT_DIR/.claude-ci"
mkdir -p "$OUTPUT_DIR"
# Step 1: Analysis
echo "Analyzing the project..."
RESULT=$(claude -p "Analyze the files modified in the last commit. \
List the files and their role." \
--output-format json)
SESSION_ID=$(echo "$RESULT" | jq -r '.session_id')
echo "$RESULT" | jq -r '.result' > "$OUTPUT_DIR/analysis.md"
# Step 2: Test generation
echo "Generating tests..."
claude -p "For each identified file, generate a Jest unit test." \
--session-id "$SESSION_ID" \
--output-format json | jq -r '.result' > "$OUTPUT_DIR/tests.md"
# Step 3: Security review
echo "Security review..."
claude -p "Identify potential vulnerabilities in these files." \
--session-id "$SESSION_ID" \
--output-format json | jq -r '.result' > "$OUTPUT_DIR/security.md"
echo "Pipeline complete. Results in $OUTPUT_DIR/"
Verification: run the script and verify that the three Markdown files are created in .claude-ci/.
To restrict the tools accessible to Claude Code in your automated scripts, the permissions and security tutorial details each option.
If you see Error: Session not found, the session_id has expired. Headless sessions have a default lifetime of 15 minutes. Restart a new session.
Key takeaway: multi-turn sessions with --session-id allow you to chain complex tasks while preserving conversational context.
What are the advanced CI/CD use cases?
Beyond code review, headless mode opens up advanced automation possibilities in your pipelines.
Step 11: Automate changelog generation (~3 min)
Configure an automatic changelog generation job:
#!/bin/bash
LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "HEAD~10")
git log "$LAST_TAG"..HEAD --pretty=format:"%h %s" | claude -p \
"Transform this list of commits into a structured changelog. \
Categories: Features, Bug Fixes, Performance, Breaking Changes. \
Markdown format with links to commits." \
--output-format text > CHANGELOG-draft.md
headless mode processes on average 15,000 input tokens per request in CI/CD pipelines. This automation reduces manual changelog writing time by 85%.
Step 12: Create a quality gate with scoring (~3 min)
Implement a quality gate that blocks the PR if the score is insufficient:
#!/bin/bash
SCORE=$(claude -p "Analyze this diff and assign a quality score from 0 to 100. \
Criteria: readability, error coverage, conventions. \
Reply ONLY with the number." \
--output-format text | tr -d '[:space:]')
echo "Quality score: $SCORE/100"
if [ "$SCORE" -lt 70 ]; then
echo "Insufficient score ($SCORE < 70). PR blocked."
exit 1
fi
echo "Acceptable score ($SCORE >= 70). PR validated."
You can explore more headless mode usage tips to refine your automations.
Usage with other CI platforms
Headless mode works with all major CI/CD platforms. Adapt the configuration to your environment:
| CI Platform | Secret variable | Installation command |
|---|---|---|
| GitHub Actions | secrets.ANTHROPIC_API_KEY | npm i -g @anthropic-ai/claude-code |
| GitLab CI | $ANTHROPIC_API_KEY (CI variable) | npm i -g @anthropic-ai/claude-code |
| Jenkins | Credentials binding | sh 'npm i -g @anthropic-ai/claude-code' |
| CircleCI | Context / env variable | npm i -g @anthropic-ai/claude-code |
In practice, 92% of teams using Claude Code in CI/CD choose GitHub Actions as their primary platform, followed by GitLab CI at 5%.
Check out the headless mode FAQ for frequently asked questions about multi-platform compatibility.
Verification: run your quality gate script on a test file and verify that it returns a numeric score.
Key takeaway: headless mode adapts to all CI/CD use cases - changelogs, quality gates, documentation, tests - on any platform.
How to secure and optimize your headless pipelines?
Security and performance are major concerns when integrating AI into your automated pipelines.
Restrict available tools with --allowedTools to limit the attack surface:
# Read-only: Claude can only read and search
claude -p "Analyze this code" \
--allowedTools "Read,Grep,Glob" \
--output-format json
The --allowedTools flag accepts a comma-separated list. In CI/CD mode, SFEIR Institute recommends always restricting tools to the strict minimum. The Bash tool should be excluded in review pipelines to prevent uncontrolled code execution.
To master the essential commands available in Claude Code, refer to the slash commands tutorial.
| Security profile | Allowed tools | Use case |
|---|---|---|
| Read-only | Read,Grep,Glob | Code review, analysis |
| Controlled editing | Read,Grep,Glob,Edit | Automatic refactoring |
| Full | All | Project generation (sandbox) |
The average cost of a headless execution is $0.01 to $0.05 depending on context size. For a pipeline processing 50 PRs per day, this represents approximately $50 per month.
If you want to dive deeper into all the headless mode and CI/CD possibilities, the reference page covers each option in detail.
If you seeError: Tool not allowed, verify that the tool required by the prompt is in the--allowedToolslist.
Key takeaway: always restrict tools to the minimum necessary and budget your API costs based on PR volume.
How to go further with Claude Code in CI/CD?
This tutorial has shown you the fundamentals of headless mode. Here are the next steps to deepen your mastery.
Explore these complementary resources to refine your configuration:
- Persistent memory: the CLAUDE.md system allows you to store reusable instructions between headless sessions
- Advanced formats: the headless mode cheatsheet summarizes all CLI options on a single page
- Troubleshooting: the headless mode FAQ covers the 15 most frequent errors
- Best practices: the advanced tips detail proven automation patterns
To build skills in a structured way, SFEIR Institute offers the Claude Code training over one day, with hands-on labs covering headless mode and CI/CD integration. If you want to go beyond and integrate AI into your entire development workflow, the AI-Augmented Developer training over two days covers complete automation strategies.
For already experienced practitioners, the AI-Augmented Developer - Advanced training in one day dives deeper into advanced CI/CD use cases and multi-agent architectures.
Headless mode is a tool that improves with practice. Start with a simple use case - automatic code review - then gradually expand your automation coverage.
Key takeaway: Claude Code's headless mode transforms your CI/CD pipeline into an intelligent assistant capable of analyzing, generating, and validating code at every commit.
Claude Code Training
Master Claude Code with our expert instructors. Practical, hands-on training directly applicable to your projects.
View program