Reference13 min read

Headless Mode and CI/CD - Command Reference

SFEIR Institute

TL;DR

Claude Code's headless mode lets you run prompts directly from the terminal or a CI/CD pipeline, without an interactive interface. This reference guide details the `-p` flag syntax, available output formats, and GitHub Actions integrations to automate your development workflows.

Claude Code's headless mode lets you run prompts directly from the terminal or a CI/CD pipeline, without an interactive interface. This reference guide details the -p flag syntax, available output formats, and GitHub Actions integrations to automate your development workflows.

Claude Code's headless mode and CI/CD is a set of commands and flags that transform the AI agent into a scriptable tool for automation. Claude Code v1.0.33 supports three output formats (text, json, stream-json) and integrates natively into GitHub Actions, GitLab CI, and Jenkins pipelines. more than 40% of advanced users leverage headless mode in at least one CI/CD workflow.

What are the most commonly used headless commands?

Here is the quick reference table of essential headless mode commands. Each command works without an interactive interface and returns an exit code usable in your scripts.

CommandDescriptionExample
claude -p "prompt"Runs a single promptclaude -p "Explain this file"
claude -p --output-format jsonStructured JSON outputclaude -p "Analyze" --output-format json
claude -p --output-format stream-jsonStreaming JSON outputclaude -p "Summarize" --output-format stream-json
claude -p -m sonnetChoose the modelclaude -p "Review" -m claude-sonnet-4-6
claude -p --max-turns NLimit agent turnsclaude -p "Fix bug" --max-turns 5
claude -p --allowedToolsRestrict toolsclaude -p "Lint" --allowedTools Bash,Read
claude -p --session-id IDResume a sessionclaude -p "Continue" --session-id abc123
claude -p < file.txtPrompt from a fileclaude -p < instructions.txt
`echo "prompt" \claude -p`Prompt via stdin pipe`git diff \claude -p "Review this diff"`
claude -p --verboseVerbose mode (debug)claude -p "Test" --verbose

For a general overview of how it works, check out the complete headless mode and CI/CD guide which covers the fundamental concepts.

Key takeaway: the -p flag (print) is the single entry point to headless mode - it disables the interactive interface and sends the response to stdout.

How to use the -p flag to run Claude Code in a single command?

The -p flag (or --print) is the fundamental headless mode command. Pass your prompt in quotes directly after the flag. Claude Code processes the request, displays the response on stdout, then terminates the process.

# Simple one-line prompt
claude -p "Generate a Python quicksort function"

# Multi-line prompt with heredoc
claude -p <<'EOF'
Analyze this code and suggest improvements:
- Performance
- Readability
- Missing tests
EOF

The -p flag accepts context via stdin. In practice, this combination with Unix pipes covers 80% of headless use cases.

# Pipe file content
cat src/utils.ts | claude -p "Add the missing TypeScript types"

# Pipe a Git diff for automatic review
git diff HEAD~1 | claude -p "Review this diff, list potential issues"

Here is how to combine multiple flags for precise execution control. The base command reference details the flags shared between interactive and headless modes.

FlagSyntaxDescriptionDefault value
-p, --printclaude -p "prompt"Enables headless modeDisabled
-m, --model-m claude-sonnet-4-6Selects the modelclaude-sonnet-4-6
--max-turns--max-turns 10Limits agentic turnsUnlimited
--allowedTools--allowedTools Bash,ReadRestricts allowed toolsAll
--disallowedTools--disallowedTools WriteForbids certain toolsNone
--verbose--verboseEnables detailed logsDisabled
--no-user-prompt--no-user-promptDisables user promptsDisabled

Headless mode returns an exit code of 0 on success and a non-zero code on error, allowing it to integrate into conditional scripts with && or ||.

Key takeaway: combine -p with Unix pipes to inject context (files, diffs, logs) directly into your prompt.

How to integrate Claude Code into GitHub Actions?

GitHub Actions is the most common CI/CD platform for automating Claude Code in headless mode. Configure your YAML workflow by storing your API key in the repository secrets. 65% of open-source projects use GitHub Actions as their primary CI pipeline.

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 code review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          git diff origin/main...HEAD | claude -p \
            "Review this diff. List bugs, security flaws, and suggestions." \
            --output-format json > review.json

To avoid frequent authentication and permission errors, check out the common headless mode errors page which lists the most frequent error messages.

Concretely, limit the API cost by adding --max-turns 3 in your review workflows. Each agentic turn consumes additional tokens - a standard diff review rarely needs more than 2 turns.

      - name: Generate changelog
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          git log --oneline origin/main...HEAD | claude -p \
            "Generate a structured Markdown changelog" \
            --max-turns 1 \
            --output-format text > CHANGELOG_PR.md

The ANTHROPIC_API_KEY environment variable is the only required secret. Store this key in the GitHub repository settings under Settings > Secrets and variables > Actions.

Key takeaway: always add --max-turns in your CI workflows to control costs and execution duration.

What output formats are available and how to parse them?

Claude Code in headless mode supports three distinct output formats. Choose the format suited to your use case: text for human reading, json for programmatic parsing, stream-json for real-time processing.

FormatFlagReturned contentUse case
text--output-format textPlain text (stdout)Simple scripts, direct reading
json--output-format jsonComplete JSON objectParsing, post-processing, storage
stream-json--output-format stream-jsonJSON events line by lineReal-time streaming, dynamic UIs

How to use the text format?

The text format is the default mode. The response is displayed directly on stdout without a wrapper or metadata. Redirect the output with > or parse it with standard Unix tools.

# Text output redirected to a file
claude -p "Generate a README for this project" --output-format text > README.md

# Extract a specific line
claude -p "List obsolete dependencies" | grep "CRITICAL"

How to use the json format?

The json format returns a structured object containing the response, session metadata, and token statistics. Use jq to extract the relevant fields.

# Extract the response only
claude -p "Analyze this code" --output-format json | jq -r '.result'

# Extract the token cost
claude -p "Summarize this file" --output-format json | jq '.usage'

The returned JSON structure contains between 5 and 8 fields depending on the context. In practice, the .result field contains the text response and .usage.output_tokens indicates the number of generated tokens.

To go further on command combinations, the headless mode examples page offers ready-to-use scripts.

How to use the stream-json format?

The stream-json format emits one JSON event per line (NDJSON). Each event contains a type (assistant, tool_use, result) and a partial payload. Process this stream with an NDJSON parser like jq --stream or a Node.js library.

# Read the stream in real time
claude -p "Refactor this module" --output-format stream-json | \
  while IFS= read -r line; do
    echo "$line" | jq -r 'select(.type == "assistant") | .content'
  done

Key takeaway: use json for automated post-processing and stream-json for real-time integrations (dashboards, notifications).

How to manage programmatic multi-turn sessions?

A multi-turn session maintains context between multiple successive headless calls. Retrieve the session identifier after the first call, then reuse it with --session-id to continue the conversation.

# First call: retrieve the session ID
RESPONSE=$(claude -p "Analyze the architecture of this project" --output-format json)
SESSION_ID=$(echo "$RESPONSE" | jq -r '.session_id')

# Second call: continue in the same session
claude -p "Now, propose a refactoring plan" \
  --session-id "$SESSION_ID" \
  --output-format json > plan.json

# Third call: request implementation
claude -p "Implement point 1 of the plan" \
  --session-id "$SESSION_ID" \
  --max-turns 5

The session identifier is a 36-character UUID. Each session preserves the full exchange history, which increases token consumption with each turn. In practice, a 5-turn session consumes on average 3 times more tokens than a single call.

You can also resume an existing session from history. Check out the first conversations cheatsheet to understand conversational context management.

ParameterRoleExample
--session-idResume an existing session--session-id a1b2c3d4
--resumeResume the last sessionclaude --resume
--continueContinue the current sessionclaude --continue
--max-turnsLimit the number of turns--max-turns 10

Concretely, multi-turn sessions are useful for multi-step workflows: analysis > planning > implementation > validation.

Key takeaway: limit your multi-turn sessions to 5-7 turns maximum to control token consumption and avoid context degradation.

What are the advanced CI/CD use cases?

Beyond simple code review, Claude Code in headless mode covers advanced automation scenarios. Here is how to use it for documentation generation, automated testing, and security analysis.

Automatic documentation generation

# Generate JSDoc for all modified TypeScript files
git diff --name-only origin/main...HEAD -- '*.ts' | \
  xargs -I {} claude -p "Add the missing JSDoc to this file: $(cat {})" \
  --max-turns 1 > docs_output.txt

Automated security analysis

# Scan for vulnerabilities in the diff
git diff origin/main...HEAD | claude -p \
  "Analyze this diff to detect: SQL injection, XSS, exposed secrets, vulnerable dependencies. JSON format." \
  --output-format json \
  --allowedTools Read \
  --max-turns 2 > security_report.json

The --allowedTools Read restriction guarantees that Claude Code does not modify any file during the analysis. 70% of vulnerabilities detected in CI come from third-party dependencies.

To discover more advanced automations, the first conversations tips share prompting techniques applicable to headless mode.

Automated testing and validation

# Verify that code follows ESLint and Prettier conventions
claude -p "Verify that this code follows ESLint and Prettier conventions" \
  --allowedTools Bash,Read \
  --max-turns 3

# Generate unit tests for modified files
git diff --name-only HEAD~1 -- '*.ts' | \
  xargs -I {} claude -p "Generate Jest tests for {}" \
  --max-turns 2

SFEIR Institute offers the AI-Augmented Developer - Advanced training over 1 day, which covers precisely the integration of Claude Code into CI/CD pipelines with hands-on labs on GitHub Actions and GitLab CI.

Key takeaway: always restrict allowed tools (--allowedTools) in CI workflows to guarantee execution security and predictability.

How to combine the most frequent headless commands?

Here are the most useful one-liners for your daily workflows. Each combination leverages Unix pipes and headless flags to solve a concrete problem.

# Complete PR review with JSON report
git diff origin/main...HEAD | claude -p "Detailed code review" --output-format json | jq '.result' > review.md

# Automatic commit message based on the diff
git diff --staged | claude -p "Generate a conventional commit message (type: description)" --max-turns 1

# Summary of a log file
tail -n 500 app.log | claude -p "Summarize the critical errors from the last 500 lines" --output-format text

# Code conversion with model constraint
cat legacy.py | claude -p "Convert this Python 2 code to Python 3.12" -m claude-sonnet-4-6 --max-turns 1

# Automatic API documentation
cat src/api/routes.ts | claude -p "Generate OpenAPI 3.1 documentation in YAML" > openapi.yaml

Run these combinations directly in your terminal or integrate them into Makefiles. The slash commands reference complements this list with commands available in interactive mode.

You can also chain commands with conditions. Concretely, a 3-step validation pipeline fits in a single line:

# Pipeline: lint > review > test generation
claude -p "Lint this file" --max-turns 1 && \
claude -p "Review the remaining issues" --max-turns 2 && \
claude -p "Generate the missing tests" --max-turns 3

Key takeaway: chain your headless commands with && to create robust sequential pipelines - each step only runs if the previous one succeeds.

What keyboard shortcuts accelerate the headless workflow?

In headless mode, keyboard shortcuts primarily apply during the development and testing phase of prompts in interactive mode, before porting them to your scripts.

ShortcutActionContext
Ctrl+CInterrupt the current executionHeadless and interactive
Ctrl+DSend EOF (end of stdin)Pipe and heredoc
Up arrowRecall the last commandTerminal (zsh/bash)
Ctrl+RSearch historyTerminal (zsh/bash)
TabFlag autocompletionAfter installing the completion script
EscapeCancel the current promptInteractive mode only

Enable autocompletion to save time on flag entry. The installation cheatsheet explains how to configure the completion script for your shell.

You can also create shell aliases for your frequent headless commands. Add these lines to your .zshrc or .bashrc:

# Aliases for frequent headless commands
alias cr='claude -p "Code review of the staged diff" --max-turns 2'
alias cfix='claude -p "Fix the errors in this file" --max-turns 3'
alias cdoc='claude -p "Generate the documentation" --max-turns 1'
alias ctest='claude -p "Generate unit tests" --max-turns 2'

The SFEIR Claude Code one-day training lets you practice these headless commands with guided exercises, from the first -p flag to complete CI/CD integration.

Key takeaway: create shell aliases for your 5 most frequent headless commands - you will save on average 15 seconds per invocation.

How to configure permissions and security in CI/CD?

CI/CD security in headless mode relies on three mechanisms: tool restriction, environment variables, and timeouts. Configure these parameters before any production deployment.

# Secure execution: limited tools + timeout
timeout 120 claude -p "Analyze this code" \
  --allowedTools Read,Grep,Glob \
  --max-turns 2 \
  --no-user-prompt

The --no-user-prompt flag prevents Claude Code from requesting user confirmation, which would block a non-interactive pipeline. The system timeout (120 seconds in this example) protects against infinite executions.

Environment variableRoleRequired
ANTHROPIC_API_KEYAnthropic API keyYes
CLAUDE_CODE_MAX_TOKENSToken limit per requestNo
CLAUDE_CODE_MODELDefault modelNo
CIAutomatic CI mode detectionAuto
CLAUDE_CODE_DISABLE_TELEMETRYDisable telemetryNo

Verify that your API key has the minimum required permissions. In practice, a dedicated CI key with a monthly budget capped at $50 covers most review and documentation workflows.

To configure custom commands usable in headless mode, the custom commands and skills reference details the configuration file syntax.

To master all these automation techniques, the AI-Augmented Developer training over 2 days covers the complete integration of AI into your development workflow, from fundamentals to advanced CI/CD patterns.

Key takeaway: always isolate your CI API keys in dedicated secrets and cap the budget to avoid billing surprises.

Can you debug failing headless executions?

Debugging in headless mode follows a systematic approach. Enable verbose mode, check exit codes, and inspect logs to identify the failure cause.

# Verbose mode for diagnostics
claude -p "Command that fails" --verbose 2> debug.log

# Check the exit code
claude -p "Test" --max-turns 1; echo "Exit code: $?"

Exit codes follow Unix convention: 0 means success, 1 means general error, 2 means argument error. 85% of headless errors come from three causes: invalid API key, timeout exceeded, or unauthorized tool.

Check out the complete list of error messages on the common headless mode errors page for quick diagnosis.

Test your prompts in interactive mode before deploying them in CI. The conversation tips offer formulation techniques that reduce errors by 30% on average.

Key takeaway: systematically test your headless commands locally with --verbose before integrating them into a CI/CD pipeline.


Recommended training

Claude Code Training

Master Claude Code with our expert instructors. Practical, hands-on training directly applicable to your projects.

View program