Claude Code Headless Mode
Claude Code is designed for interactive use, but its --print flag unlocks fully non-interactive automation. This page covers every headless pattern: CI pipelines, shell scripts, Docker containers, and batch processing โ with working examples for each.
The Core Flag: --print (alias: -p)
By default, claude opens an interactive REPL. Add --print to get a single response to stdout and exit:
# Interactive (default) โ opens a chat session
claude
# Non-interactive โ prints response and exits
claude --print "What does this repo do?"
claude -p "List all exported functions in src/"
--print flag is the single most important flag for automation. Everything else in this guide builds on it.Key Flags Reference
| Flag | Env var equivalent | Effect |
|---|---|---|
| --print / -p | โ | Non-interactive: print response to stdout and exit |
| --output-format json | โ | Return structured JSON (includes token counts, model used) |
| --auto-accept-edits | CLAUDE_AUTO_ACCEPT_EDITS=1 | Apply all file edits without confirmation prompts |
| --dangerously-skip-permissions | โ | Skip all permission confirmation prompts (use in isolated containers only) |
| --model | ANTHROPIC_MODEL | Override model (e.g., --model claude-haiku-4-5-20251001 for speed) |
| --max-turns | โ | Cap the number of agentic turns (prevents runaway loops) |
| --system-prompt | โ | Override the system prompt for this run |
| --no-color | NO_COLOR=1 | Disable ANSI color codes in output (good for log files) |
Piping Input
Pass content to Claude via stdin โ useful for code review and diff analysis:
# Pipe git diff for PR description
git diff HEAD~1 | claude --print "Write a concise PR description for these changes"
# Pipe a file for analysis
cat src/auth.ts | claude --print "Find security issues in this TypeScript file"
# Pipe from a heredoc
claude --print <<'EOF'
Review this SQL query for injection vulnerabilities:
SELECT * FROM users WHERE id = '$userId'
EOF
JSON Output Mode
Use --output-format json to get a machine-parseable response. Combine with jq to extract the text:
# Get structured response
claude --print --output-format json "List the top 3 bugs in src/" | jq -r '.result'
# Example JSON shape returned:
# {
# "result": "1. Missing null check at line 42...",
# "model": "claude-sonnet-4-6",
# "input_tokens": 2341,
# "output_tokens": 187
# }
GitHub Actions Integration
Add ANTHROPIC_API_KEY to your repository Secrets, then use Claude Code in a workflow step:
# .github/workflows/ai-review.yml
name: AI Code Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Run AI review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
git diff HEAD~1 | claude --print --no-color \
"Review this diff. Focus on: bugs, security issues, missing error handling. \
Output as markdown with a Verdict (PASS/NEEDS CHANGES) at the top." \
| tee review.md
- name: Post review as PR comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs')
const body = fs.readFileSync('review.md', 'utf8')
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '## AI Code Review\n\n' + body
})
Docker Container Setup
Run Claude Code in a Docker container โ useful for isolated CI environments:
# Dockerfile
FROM node:20-slim
RUN npm install -g @anthropic-ai/claude-code
WORKDIR /workspace
ENTRYPOINT ["claude"]
# Build and run
docker build -t claude-code-runner .
docker run --rm \
-e ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \
-v "$(pwd)":/workspace \
claude-code-runner \
--print --dangerously-skip-permissions \
"Add JSDoc comments to all exported functions"
--dangerously-skip-permissions bypasses all confirmation prompts and will apply file edits without asking. Only use it in isolated containers or CI environments where you control the input and can roll back via git.Shell Script Patterns
#!/usr/bin/env bash
# Nightly code health check
set -euo pipefail
export ANTHROPIC_API_KEY="$(cat ~/.anthropic-key)"
# Analyze each changed file
git diff --name-only HEAD~7 HEAD -- '*.py' | while read -r file; do
echo "=== Reviewing $file ==="
claude --print --model claude-haiku-4-5-20251001 \
"In 3 sentences, summarize the quality of this file and flag any issues:" \
"$(cat "$file")"
done
# Generate weekly changelog from commits
git log --oneline HEAD~7..HEAD \
| claude --print "Convert these commits to a user-facing changelog. Group by: Features, Fixes, Other."
Batch Processing Files
#!/usr/bin/env bash
# Add type hints to all Python files in parallel
find . -name "*.py" -not -path "./.venv/*" | head -20 | while read -r f; do
(
echo "Adding type hints to $f"
claude --print --auto-accept-edits \
"Add Python type hints to all function signatures in this file. \
Do not change logic. Only add annotations." \
< "$f" > /dev/null
) &
done
wait
echo "Done"
Environment Variable Configuration
| Variable | Purpose | Example |
|---|---|---|
| ANTHROPIC_API_KEY | Required โ your API key | sk-ant-... |
| ANTHROPIC_MODEL | Override default model | claude-haiku-4-5-20251001 |
| CLAUDE_AUTO_ACCEPT_EDITS | Skip edit confirmation prompts | 1 |
| NO_COLOR | Disable ANSI colors in output | 1 |
| ANTHROPIC_BASE_URL | Custom API endpoint (proxies, AWS Bedrock) | https://... |
Cost Control in Automation
Tips to keep automation costs predictable
Use --model claude-haiku-4-5-20251001 for high-volume tasks (10ร cheaper than Sonnet). Cap turns with --max-turns 5 to prevent runaway agentic loops. Set a small --max-tokens for output-bounded tasks like changelog generation. Monitor token usage with --output-format json | jq .input_tokens,.output_tokens. See Claude Cost Calculator for accurate per-run cost estimates.
Frequently Asked Questions
How do I run Claude Code non-interactively?
Use the --print flag: claude --print "your prompt". This prints the response to stdout and exits. No interactive session is opened.
How do I use Claude Code in GitHub Actions?
Store ANTHROPIC_API_KEY in repository Secrets. In your workflow: npm install -g @anthropic-ai/claude-code then claude --print --no-color "your prompt". Pipe git diff for automated reviews.
What is --auto-accept-edits?
It tells Claude Code to apply all file edits without asking for confirmation โ essential for fully automated pipelines. Pair with version control so you can git diff and revert if needed.
Can Claude Code run in Docker?
Yes. Install Node.js + Claude Code in the container, mount your code as a volume, and set ANTHROPIC_API_KEY as an env var. Use --dangerously-skip-permissions in isolated containers to skip all prompts.
How do I pipe code to Claude from a shell script?
Pipe via stdin: cat file.py | claude --print "review this" or use git diff: git diff HEAD~1 | claude --print "summarize changes".
What does --output-format json return?
A JSON object with result (the response text), model, input_tokens, and output_tokens. Parse with jq -r '.result' to extract just the text.