Home AI SkillsClaude Code Headless Mode: Use claude -p in Scripts and CI Pipelines

Claude Code Headless Mode: Use claude -p in Scripts and CI Pipelines

by Knowledge Base Linux
Claude Code headless mode — automated agent runs inside a server pipeline

Everything Claude Code does interactively, it can also do without a human at the keyboard. Claude Code headless mode — activated by the -p (or --print) flag — runs the agent non-interactively: you pass a prompt, it does the work, prints the result and exits. That one flag turns Claude Code into a Unix citizen that composes with pipes, cron jobs, shell scripts and CI pipelines, which is exactly where a Linux audience will get the most leverage out of it.

Claude Code Headless Mode Basics

# Ask a question about a codebase
claude -p "explain what the worker service in this repo does"

# Pipe input straight in — logs, diffs, anything textual
cat /var/log/nginx/error.log | claude -p "what caused these errors? summarize the top 3 issues"
git diff main | claude -p "review this diff for security issues"

The pattern to notice: stdin becomes context, the prompt becomes the instruction, stdout becomes a result you can redirect, save or feed to the next tool in the chain. If you have used our guide to calling LLM APIs from Bash, headless mode is the higher-level version of the same idea — but with file access, tools and your whole project available to the agent, not just the text you paste.

Machine-Readable Output for Scripts

Plain text is for humans; automation wants structure. Headless mode offers three output formats:

# Single JSON object: result, session_id, usage and total cost
claude -p "list all TODO comments in src/" --output-format json

# Parse it like any other tool
claude -p "did the deploy config change?" --output-format json | jq -r '.result'

# Stream events as they happen (for long jobs and live UIs)
claude -p "run the test suite and fix failures" --output-format stream-json

For strict consumers, --json-schema constrains the reply to a JSON Schema you provide, so downstream code can rely on the shape instead of parsing prose. The JSON result also carries the session ID, which pairs with the session flags below.

Claude Code headless mode powering a continuous integration pipeline

Permissions: The Flag That Decides Whether CI Works

Interactive Claude Code asks before it edits files or runs commands. Nobody can answer prompts in a pipeline, so headless runs need an explicit permission strategy:

# Allow only the tools this job needs
claude -p "run tests and fix failures" --allowedTools "Bash,Read,Edit"

# Auto-accept file edits (but not arbitrary approvals)
claude -p "apply the lint fixes" --permission-mode acceptEdits

# Explicitly block dangerous operations
claude -p "clean up this repo" --disallowedTools "Bash(rm:*),Bash(sudo:*)"

Resist the temptation of --dangerously-skip-permissions outside a disposable sandbox or container — it does exactly what the name says. Least privilege with --allowedTools, plus cost guardrails, is the professional default:

claude -p "refactor the parser module" --max-turns 10 --max-budget-usd 5.00

--max-turns caps the agent loop and --max-budget-usd caps API spend, so a confused job fails bounded instead of expensive.

Sessions, MCP and System Prompts in Automation

Headless calls can continue conversations: capture the session_id from the JSON output and pass --resume <id> later, or use --continue for the most recent session in that directory. Two more flags earn their keep in pipelines:

  • --mcp-config ./ci-servers.json — load MCP servers from a file for this run only.
  • --append-system-prompt "You are reviewing for a regulated codebase; flag any PII logging" — add standing instructions without changing the prompt itself.
  • --no-session-persistence — keep CI runs ephemeral.
  • --model haiku — pick a cheaper model for simple, high-volume jobs.

Putting It in CI: Two Working Patterns

GitHub Actions. Anthropic publishes an official action (anthropics/claude-code-action) that wires Claude into pull requests — automatic reviews, responding to @-mentions in comments, and applying requested fixes — authenticated with an API key or a Claude subscription OAuth token stored as a repository secret.

Any other CI (GitLab, Jenkins, plain cron). Install the CLI on the runner, set ANTHROPIC_API_KEY as a masked CI variable, and call claude -p with tight --allowedTools, --max-turns and --max-budget-usd. Good first jobs: nightly test-failure triage summaries posted to your chat, dependency-update explanations, documentation drift checks, and pre-merge diff reviews like the ones we described for AI-assisted incident workflows.

Claude Code Headless Mode: Tips from the Field

  • Write prompts for a reader who cannot ask questions: goal, scope, constraints and definition of done, all explicit.
  • Prefer several small, single-purpose invocations over one giant prompt — each run is easier to permission, budget, log and retry when something goes wrong.
  • Start every automation read-only (Read, Grep, Glob) and grant write tools only after the read-only version proves itself.
  • Log the JSON output of every run — cost and session data make debugging and budgeting trivial.
  • Pin the CLI version on CI runners so behavior changes arrive on your schedule, not mid-incident.

The complete flag reference is in Anthropic’s official headless mode documentation. Master claude -p and Claude Code stops being a tool you visit and becomes a stage in your pipelines.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.