Claude Tips mascot
Claude Tips & Tricks
Claude Code advanced

Use Claude Code Headless Mode for Automation

The -p flag runs Claude Code non-interactively for scripting, CI/CD integration, and Unix pipe workflows.

Claude Code’s -p (print/pipe) flag lets you run it non-interactively. Instead of the interactive chat interface, Claude processes input from stdin, prints the result to stdout, and exits. This is how you script it.

Basic usage:

# Ask a quick question
claude -p "What does the MIT license allow?"

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

# Review a git diff
git diff HEAD~1 | claude -p "Review this diff for bugs"

CI/CD integration:

# Auto-review PRs in GitHub Actions
git diff origin/main...HEAD | claude -p \
  "Review this PR diff for security vulnerabilities" \
  --output-format json \
  --allowedTools Read \
  --max-turns 5

Key flags for headless mode:

  • --output-format json - get structured JSON output instead of plain text
  • --allowedTools Read,Write - restrict which tools Claude can use (security best practice)
  • --max-turns 5 - prevent infinite loops by capping the number of agent turns
  • --append-system-prompt "..." - add extra instructions while keeping default behavior

Cost note: A typical headless review pipeline consumes around 8,000 tokens per run, roughly $0.02 with the Claude API. Combine with the Batch API for bulk operations at 50% off.

Paste into Claude Code
Create a shell script that uses claude -p to automate code review on all changed files in the current branch compared to main.