Claude Code Batch Processing Complete Guide: /batch Command and Headless Mode in Practice¶
The /batch command in Claude Code shines when you need to apply the same transformation across hundreds of files. It runs up to 10x faster than sending individual prompts and integrates directly into CI/CD pipelines.
Key Points
- The
/batchcommand executes codebase-wide migrations safely using parallel agents + Git Worktree isolation - Headless mode (
claude -p) provides non-interactive integration for CI/CD pipelines and shell scripts - The two serve distinctly different use cases and can be combined to automate the entire development workflow
Audience:
Intermediate to advanced Claude Code users looking to scale up with large-scale changes and CI/CD integration
/batch Command vs. Headless Mode¶
/batch and claude -p are often confused, but they serve entirely different purposes. The former automates codebase-wide migrations with parallel agents. The latter is a non-interactive execution mode for embedding AI processing into CI/CD pipelines.
| Aspect | /batch Command | Headless Mode (claude -p) |
|---|---|---|
| Execution | Slash command within an interactive session | One-shot execution from terminal |
| Primary Use | Codebase-wide migration and refactoring | CI/CD integration, script automation, pipe processing |
| Parallelism | Automatically spawns multiple agents in parallel | Parallel control via shell scripts |
| Git Integration | Git Worktree isolation per agent, automatic PR creation | Standard Git operations (script-dependent) |
| Introduced In | v2.1.63+1 | Available since initial release |
Choose /batch when applying bulk changes across an entire project. Choose headless mode when embedding AI processing into existing CI/CD pipelines.
/batch Command: Parallel Execution of Large-Scale Code Changes¶
Basic Usage¶
/batch is a slash command executed within an interactive Claude Code session1. Simply describe the desired change in natural language, and it handles codebase investigation, implementation, and PR creation automatically.
/batch migrate from React to Vue
/batch replace all uses of lodash with native equivalents
/batch add type annotations to all untyped function parameters
/batch rename all database columns from camelCase to snake_case
When executed, an internal orchestrator agent launches and processes the work in three phases.
The Three Internal Phases¶
Phase 1: Research and Plan
The orchestrator enters plan mode and launches an Explore agent to investigate the codebase. It identifies target files, patterns, and call sites, then decomposes the work into 5 to 30 independent units. Each unit must be independently mergeable with no dependencies on other units.
Verification methods (CLI tests, existing test suites, etc.) are also determined during planning. If no verification path can be identified, the user is prompted before execution proceeds.
Phase 2: Spawn Workers
After plan approval, one background agent is spawned per unit. All agents run simultaneously in true parallel. Each agent is configured with:
isolation: "worktree"for Git Worktree isolation- A self-contained prompt including overall goals and individual tasks
- Codebase conventions discovered during the research phase
- Test execution instructions
Each worker runs the test suite after implementation, undergoes code review via /simplify2, then commits, pushes, and creates a PR.
Phase 3: Track Progress
The orchestrator displays a status table that updates as agents complete. The final output is a summary like "22/24 units landed as PRs."
Git Worktree Isolation¶
The reliability of /batch rests on Git Worktree isolation. Each agent has its own branch and working copy, preventing interference with other agents' changes.
project/
├── .git/ # Shared Git database
├── .claude/
│ └── worktrees/
│ ├── batch-unit-1/ # Unit 1 working copy
│ ├── batch-unit-2/ # Unit 2 working copy
│ └── batch-unit-3/ # Unit 3 working copy
└── src/ # Main working tree
True parallel execution is achieved without merge conflict risk. Since each unit's output is an independent PR, failure in one unit does not affect others.
When to Use /batch¶
Well-suited tasks:
- Framework migrations (React to Vue, Jest to Vitest, etc.)
- Updating all call sites after an API contract change
- Naming convention unification (camelCase to snake_case, etc.)
- Library replacement (axios to fetch wrapper, etc.)
Unsuitable tasks:
- Changes with strong inter-file dependencies (Agent A creates a utility that Agent B imports)
- Exploratory refactoring with unclear goals
- Single-file changes
For work requiring cross-unit coordination, Agent Teams or standard Claude Code sessions are more appropriate.
Integration with /simplify¶
/simplify is a code review slash command introduced alongside /batch in v2.1.631. Three parallel review agents (code reuse, code quality, efficiency) automatically check changed files and apply fixes where needed.
# /simplify can also be used standalone
/simplify
/simplify focus on error handling
Since /batch workers run /simplify before creating PRs2, each PR is created in an auto-reviewed state. No manual chaining is required.
Headless Mode (claude -p): CI/CD and Script Integration¶
Basic Syntax¶
Adding the -p (--print) flag runs Claude Code in non-interactive mode3. It processes the prompt, outputs the result to stdout, and exits.
# Basic execution
claude -p "Explain the project architecture"
# Data processing via pipe
cat error.log | claude -p "Summarize the key errors in this log"
# File input and output redirection
claude -p "Review for security vulnerabilities" < app.py > security_report.txt
Output Formats¶
Three output formats are available, each suited to different use cases.
# Text format (default) — for human consumption
claude -p "Summarize this file" --output-format text
# JSON format — recommended for automated processing and CI/CD
claude -p "List all TODO comments" --output-format json
# Streaming JSON format — for real-time processing
claude -p "Process this large dataset" --output-format stream-json
JSON output can be processed with jq for extracting response text or checking token usage.
# Extract response text only
claude -p "Analyze this code" --output-format json | jq -r '.result'
# Check token usage
claude -p "Summarize this file" --output-format json | jq '.usage'
Tool Permission Control¶
Headless mode cannot prompt for interactive permission confirmation. Use the --allowedTools flag to explicitly specify permitted tools.
# Read-only (safe)
claude -p "Analyze the code" --allowedTools "Read,Grep,Glob"
# Limited write permissions
claude -p "Fix the bug" --allowedTools "Read,Write,Edit"
# Git operation permissions (prefix matching)
claude -p "Create a commit from staged changes" \
--allowedTools "Bash(git diff *),Bash(git log *),Bash(git commit *)"
--allowedTools supports prefix matching. Bash(git diff *) permits all commands starting with git diff. Note that spacing matters: Bash(git diff*) would also match git diff-index and similar commands.
Permission Setting Caution
The --dangerously-skip-permissions flag bypasses all permission checks unconditionally. Use only in fully isolated environments such as CI/CD containers. Not recommended for production or local development environments.
Multi-Turn Sessions¶
Session IDs allow context to persist across multiple claude -p invocations.
# First invocation
claude -p "Review performance issues"
# Continue the most recent session
claude -p "Focus on database queries" --continue
# Continue a specific session by ID
session_id=$(claude -p "Start review" --output-format json \
| jq -r '.session_id')
claude -p "Continue the review" --resume "$session_id"
Sessions retain approximately 200,000 tokens of context. However, token consumption increases with each turn. Use --max-turns to limit execution turns for cost management.
System Prompt Customization¶
Four flags control the runtime prompt.
# Add instructions while keeping defaults (recommended)
gh pr diff "$1" | claude -p \
--append-system-prompt "Review as a security engineer for vulnerabilities" \
--output-format json
# Add instructions from file (for team sharing)
claude -p "Review the code" \
--append-system-prompt-file ./review-rules.md
# Complete prompt replacement (advanced use)
claude -p "Analyze" --system-prompt "You are a senior architect."
--append-system-prompt adds instructions while preserving Claude Code's default capabilities. This is appropriate for most use cases. --system-prompt completely replaces the default instructions and should only be used when built-in features are not needed.
CI/CD Pipeline Integration¶
Since /batch is a session-internal command, it cannot be embedded in CI/CD. Headless mode (claude -p) is the tool for pipeline integration.
GitHub Actions¶
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
claude-review:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Claude Code
run: |
curl -sSL https://claude.ai/install.sh | sh
echo "$HOME/.claude/bin" >> $GITHUB_PATH
- name: Security Analysis
run: |
git diff origin/main...HEAD | claude -p \
--append-system-prompt "Analyze vulnerabilities as a security engineer" \
--output-format json > security-report.json
- name: Post Review Comment
uses: actions/github-script@v6
with:
script: |
const report = require('./security-report.json');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: report.result
});
GitLab CI¶
stages:
- analysis
- report
code_analysis:
stage: analysis
image: ubuntu:latest
before_script:
- apt-get update && apt-get install -y curl jq
- curl -sSL https://claude.ai/install.sh | sh
- export PATH="$HOME/.claude/bin:$PATH"
script:
- claude -p "Analyze maintainability issues" --output-format json
> maintainability.json
- claude -p "Check for performance bottlenecks" --output-format json
> performance.json
artifacts:
paths:
- "*.json"
expire_in: 1 week
Shell Script Batch Processing¶
#!/bin/bash
set -euo pipefail
# Batch review of multiple files
review_code() {
local file="$1"
claude -p "Review for quality and security concerns" \
--allowedTools "Read,Grep,Glob" \
--output-format json < "$file" \
| jq -r '.result'
}
echo "# Code Review Report" > review_report.md
echo "Generated: $(date)" >> review_report.md
for file in src/*.py; do
echo "Reviewing: $file"
echo -e "\n## $file\n" >> review_report.md
review_code "$file" >> review_report.md
done
echo "Review complete: review_report.md"
For parallel execution, combine with GNU parallel.
# Process files with 4 parallel workers
find src -name "*.py" | parallel -j 4 \
claude -p "Optimize this code" \
--allowedTools "Read" < {} "> optimized/{/}"
Practical Best Practices¶
When Using /batch¶
- Add
.claude/worktrees/to.gitignore. This prevents worktree contents from appearing as untracked files - Review the planning phase carefully. Verify that the proposed file decomposition is appropriate before approving execution
- Confirm independence. If shared utilities need to be created first, do so in a regular session before running
/batch
When Using Headless Mode¶
- Minimize permissions. For read-only analysis tasks,
--allowedTools "Read,Grep,Glob"is sufficient - Limit turns.
--max-turns 1to3is enough for most simple tasks - Check exit codes. 0 means success, 1 means general error, 2 means authentication error
- Use JSON output. For automated processing, use
--output-format jsonand parse withjq
Cost Optimization¶
Multi-turn sessions increase token consumption by 30-50% with each additional turn. For processing large numbers of files, individual one-shot calls may be more cost-efficient. However, for tasks where maintaining context improves analysis accuracy (such as architecture reviews), session continuation is more effective.
Choosing the right approach for each use case is the key to balancing quality and cost.
Conclusion¶
Claude Code's batch processing is built on two pillars: /batch and headless mode (claude -p).
/batch enables safe parallel execution of framework migrations and naming convention unification through Git Worktree agent isolation and automatic PR creation. Headless mode handles CI/CD pipeline and shell script integration, serving as the foundation for embedding AI reviews and automated analysis into existing workflows.
As future Claude Code updates enhance /batch's cross-unit coordination capabilities, its applicability may expand to cover changes with inter-unit dependencies that are currently out of scope. Keeping an eye on the official release notes1 is recommended.
Related Articles¶
- Claude Code Advanced Guide
- Hooks Complete Guide
- MCP Integration Practical Guide
- GitHub Actions Automation
- Command Reference (2026 Edition)
Claude Code v2.1.63 Release Notes —
/batchand/simplifywere introduced in this version. ↩↩↩↩Claude Code /simplify and /batch Guide — The behavior of each worker running
/simplifybefore PR creation is documented in third-party sources. ↩↩Claude Code CLI Reference (Official) — Specifications for
--print,--allowedTools,--append-system-prompt, and other flags. ↩