Skip to content
60 Battle-Tested Recipes

CLI Playbook

Find the recipe. Copy the command. Ship it.

Complexity:60 recipes
Getting Started9
Getting Started

Your First CLI Call

Run Claude in headless mode and get a plain text response

$ claude -p "Say exactly: Hello CLI Test" "color:#7C5CFC">--output-format text
2 gotchas
Getting Started

Parse JSON Output

Get the full metadata envelope with cost, tokens, and session ID

$ claude -p "Say exactly: Hello CLI Test" "color:#7C5CFC">--output-format json
2 gotchas
Getting Started

Stream Responses (NDJSON)

Get real-time events as NDJSON for building UIs and pipelines

$ claude -p "Explain recursion" "color:#7C5CFC">--output-format stream-json "color:#7C5CFC">--verbose
2 gotchas
Getting Started

Set a Budget Cap

Limit spending per invocation with --max-budget-usd

$ claude -p "Analyze this file" "color:#7C5CFC">--output-format json "color:#7C5CFC">--max-budget-usd 1.00
2 gotchas
Getting Started

Disable Tools for Pure Text

Run Claude with zero tool access for text generation, classification, or summarization

$ claude -p "What is 2+2?" "color:#7C5CFC">--output-format json "color:#7C5CFC">--tools ""
2 gotchas
Getting Started

Append System Prompt

Add custom rules while keeping the default system prompt intact

$ claude -p "Review auth.py" \
"color:#7C5CFC">--append-system-prompt "Focus on SQL injection and XSS. Rate each finding Critical/High/Medium/Low."
2 gotchas
Getting Started

Use Structured Output (JSON Schema)

Force Claude to return data matching an exact JSON schema via constrained decoding

$ claude -p "Extract: 'John Smith is 32 years old'" \
"color:#7C5CFC">--output-format json \
"color:#7C5CFC">--json-schema '{"type":"object","properties":{"name":{"type":"string"},"age":{"type":"integer"}},"required":["name","age"]}'
2 gotchas
Getting Started

Replace System Prompt

Override the entire default system prompt for a custom persona

$ claude -p "Tell me about yourself" \
"color:#7C5CFC">--system-prompt "You are a security auditor. Only discuss vulnerabilities." \
"color:#7C5CFC">--tools ""
2 gotchas
Getting Started

Pipe File to Claude

Feed file contents via stdin pipe for quick code review or analysis

"color:#4B5563"># Pipe a single file
$ cat src/auth.py | claude -p "Review this for security issues"
"color:#4B5563"># Pipe filtered content (saves tokens)
$ grep -n "TODO\|FIXME\|HACK" src/*.ts | claude -p "Prioritize these"
...
3 gotchas
Sessions & Workflows8
Sessions & Workflows

Continue Most Recent Session

Resume the last session in the current working directory without knowing the session ID

$ claude -p "What did we discuss?" "color:#7C5CFC">--continue
2 gotchas
Sessions & Workflows

Ephemeral Session (No Persistence)

Run a one-off query without saving session data to disk

$ claude -p "Quick question" "color:#7C5CFC">--no-session-persistence "color:#7C5CFC">--output-format json
2 gotchas
Sessions & Workflows

Handle Resume Failures

Gracefully fall back to a new session when --resume fails with an expired or corrupted ID

"color:#4B5563"># See JS code for the full pattern
2 gotchas
Sessions & Workflows

Deterministic Session IDs

Use a custom UUID for mapping sessions to database records or ticket IDs

$ claude -p "Say exactly: DETERMINISTIC_TEST" \
"color:#7C5CFC">--session-id "aaaa1111-bbbb-cccc-dddd-eeee2222ffff" \
"color:#7C5CFC">--output-format json
2 gotchas
Sessions & Workflows

Fork a Session

Branch a conversation to explore alternatives without losing the main thread

$ claude -p "Try approach B instead" \
"color:#7C5CFC">--resume "$SESSION_ID" \
"color:#7C5CFC">--fork-session \
"color:#7C5CFC">--output-format json
2 gotchas
Sessions & Workflows

Create and Resume a Session

Start a conversation, capture the session ID, and continue it later

"color:#4B5563"># Step 1: Create
$ RESULT=$(claude -p "Analyze the codebase" "color:#7C5CFC">--output-format json)
SESSION=$(echo "$RESULT" | jq -r '.session_id')
"color:#4B5563"># Step 2: Resume
$ claude -p "Now focus on the database layer" "color:#7C5CFC">--resume "$SESSION"
2 gotchas
Sessions & Workflows

Plan → Review → Execute

Three-phase workflow: generate a plan, review it, then execute with full permissions

"color:#4B5563"># 1. Plan
$ PLAN=$(claude -p "Plan refactoring of auth.py" "color:#7C5CFC">--permission-mode plan "color:#7C5CFC">--output-format json)
SESSION=$(echo "$PLAN" | jq -r '.session_id')
"color:#4B5563"># 2. Extract plan text
$ echo "$PLAN" | jq -r '.permission_denials[] | select(.tool_name=="ExitPlanMode") | .tool_input.plan'
...
2 gotchas
Sessions & Workflows

Multi-Turn Cost Tracking

Track cumulative cost across session turns by extracting total_cost_usd from each response

$ RESULT=$(claude -p "Step 1" "color:#7C5CFC">--output-format json)
SESSION=$(echo "$RESULT" | jq -r '.session_id')
COST1=$(echo "$RESULT" | jq -r '.total_cost_usd')
RESULT2=$(claude -p "Step 2" "color:#7C5CFC">--resume "$SESSION" "color:#7C5CFC">--output-format json)
COST2=$(echo "$RESULT2" | jq -r '.total_cost_usd')
...
2 gotchas
CI/CD & Automation12
CI/CD & Automation

Daily Scheduled Tasks

Run recurring prompts on a schedule using /loop or CronCreate within a session

$ /loop 5m check if the deployment finished
2 gotchas
CI/CD & Automation

Fallback Model on Overload

Automatically switch to a cheaper model when the primary model is rate-limited

$ claude -p "Review this PR" \
"color:#7C5CFC">--fallback-model claude-haiku-4-5-20251001 \
"color:#7C5CFC">--max-budget-usd 0.50 \
"color:#7C5CFC">--output-format json
2 gotchas
CI/CD & Automation

GitHub Action PR Review

Auto-review pull requests using the official Claude Code GitHub Action

"color:#4B5563"># .github/workflows/review.yml
$ - uses: anthropics/claude-code-action@v1
with:
prompt: |
Review this PR for:
1. Security vulnerabilities
...
2 gotchas
CI/CD & Automation

Custom CLI Pipeline

Build a CI/CD pipeline using Claude CLI directly in GitHub Actions

"color:#4B5563"># In a GitHub Actions step:
$ npm install -g @anthropic-ai/claude-code
RESULT=$(claude -p "Review changes" \
"color:#7C5CFC">--output-format json \
"color:#7C5CFC">--max-budget-usd 0.50 \
"color:#7C5CFC">--no-session-persistence \
...
2 gotchas
CI/CD & Automation

Cost-Capped PR Review

Review a PR with a strict budget limit and machine-parseable output

$ claude -p "Review the changes in this PR" \
"color:#7C5CFC">--from-pr "$PR_URL" \
"color:#7C5CFC">--output-format json \
"color:#7C5CFC">--max-budget-usd 0.50 \
"color:#7C5CFC">--no-session-persistence \
"color:#7C5CFC">--permission-mode bypassPermissions
2 gotchas
CI/CD & Automation

Plan Mode in CI

Generate a plan in CI, post for human review, then execute on approval

"color:#4B5563"># Step 1: Generate plan
$ PLAN_RESULT=$(claude -p "Fix all lint errors in src/" \
"color:#7C5CFC">--permission-mode plan "color:#7C5CFC">--output-format json "color:#7C5CFC">--max-budget-usd 0.50)
"color:#4B5563"># Step 2: Post plan as PR comment
$ PLAN=$(echo "$PLAN_RESULT" | jq -r '.permission_denials[] | select(.tool_name=="ExitPlanMode") | .tool_input.plan')
...
2 gotchas
CI/CD & Automation

Batch File Processing

Process multiple files independently with per-file budget caps and cost tracking

$ for file in src/**/*.ts; do
claude -p "Add JSDoc comments to $file" \
"color:#7C5CFC">--output-format json \
"color:#7C5CFC">--max-budget-usd 0.10 \
"color:#7C5CFC">--no-session-persistence \
"color:#7C5CFC">--permission-mode bypassPermissions
...
2 gotchas
CI/CD & Automation

Retry with Backoff

Handle transient API failures (network errors, timeouts, 500s) with exponential retry logic

$ retry_claude() {
local max=3 prompt="$1"; shift
for attempt in $(seq 1 "$max"); do
if RESULT=$(claude -p "$prompt" "$@" 2>/dev/null); then
if echo "$RESULT" | jq -e '.is_error != true' >/dev/null 2>&1; then
echo "$RESULT"; return 0
...
2 gotchas
CI/CD & Automation

Audit Logging with Hooks

Log every tool call to a file using PostToolUse hooks for compliance and debugging

"color:#4B5563"># .claude/settings.json
$ {
"hooks": {
"PostToolUse": [
{
"hooks": [{
...
2 gotchas
CI/CD & Automation

Multi-Repo Batch Operations

Run Claude across multiple repositories in a single automated sweep

$ for repo in repo1 repo2 repo3; do
echo "=== $repo ==="
(cd "$repo" && CLAUDECODE="" claude -p \
"Summarize recent changes and flag any issues" \
"color:#7C5CFC">--output-format json \
"color:#7C5CFC">--max-budget-usd 0.50 \
...
2 gotchas
CI/CD & Automation

@claude GitHub Trigger

Trigger Claude Code reviews by mentioning @claude in PR comments via GitHub Actions

"color:#4B5563"># .github/workflows/claude.yml
$ name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
...
3 gotchas
CI/CD & Automation

Pipe Git Diff for Review

Send staged or unstaged changes to Claude for automated code review

"color:#4B5563"># Review staged changes (what you're about to commit)
$ git diff "color:#7C5CFC">--staged | claude -p "Review these changes" "color:#7C5CFC">--output-format text
"color:#4B5563"># Review only TypeScript changes
$ git diff "color:#7C5CFC">--staged -- '*.ts' '*.tsx' | \
claude -p "Review for type safety issues"
...
3 gotchas
Security & Permissions8
Security & Permissions

Allowlist Specific Tools

Restrict Claude to only specific tools using --allowedTools and --disallowedTools

$ claude -p "List and read files" \
"color:#7C5CFC">--allowedTools "Read,Glob,Grep" \
"color:#7C5CFC">--disallowedTools "Write,Edit,Bash,WebFetch,WebSearch" \
"color:#7C5CFC">--output-format json
2 gotchas
Security & Permissions

Sandboxed Execution

Run Claude with OS-level filesystem sandbox and extended directory access via --add-dir

$ claude -p "Analyze logs in /var/log/app" \
"color:#7C5CFC">--add-dir /var/log/app \
"color:#7C5CFC">--add-dir /etc/app-config \
"color:#7C5CFC">--output-format json
2 gotchas
Security & Permissions

Network-Isolated Mode

Block all web access while keeping file tools available for air-gapped analysis

$ claude -p "Analyze this code offline" \
"color:#7C5CFC">--disallowedTools "WebFetch,WebSearch" \
"color:#7C5CFC">--permission-mode bypassPermissions \
"color:#7C5CFC">--output-format json
2 gotchas
Security & Permissions

Strict MCP Config

Fail fast if any MCP server can't connect instead of silently degrading

$ claude -p "Run audit" \
"color:#7C5CFC">--mcp-config ./mcp-config.json \
"color:#7C5CFC">--strict-mcp-config \
"color:#7C5CFC">--output-format json
2 gotchas
Security & Permissions

Read-Only Agent

Lock Claude to read-only file access — the correct pattern using BOTH allowedTools and disallowedTools

$ claude -p "Analyze this codebase for security issues" \
"color:#7C5CFC">--allowedTools "Read,Grep,Glob" \
"color:#7C5CFC">--disallowedTools "Write,Edit,Bash,WebFetch,WebSearch" \
"color:#7C5CFC">--permission-mode bypassPermissions \
"color:#7C5CFC">--output-format json
2 gotchas
Security & Permissions

Permission Modes Comparison

Choose the right permission mode for your use case: default, acceptEdits, plan, dontAsk, or bypassPermissions

"color:#4B5563"># Interactive development (default)
$ claude
"color:#4B5563"># Trusted editing sessions
$ claude "color:#7C5CFC">--permission-mode acceptEdits
...
2 gotchas
Security & Permissions

Block Dangerous Commands (Hooks)

Use PreToolUse hooks to block rm -rf, DROP TABLE, and other destructive commands

"color:#4B5563"># .claude/settings.json
$ {
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
...
2 gotchas
Security & Permissions

AI-Powered Command Validation

Use a prompt-type hook to have a second AI model validate commands before execution

"color:#4B5563"># .claude/settings.json
$ {
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
...
2 gotchas
MCP & Plugins7
MCP & Plugins

Connect an MCP Server

Add an MCP server inline to extend Claude with external tools (filesystem, database, browser)

$ claude -p "List files in /tmp" \
"color:#7C5CFC">--mcp-config '{"mcpServers":{"filesystem":{"command":"npx","args":["-y","@anthropic-ai/mcp-server-filesystem","/tmp"]}}}'
2 gotchas
MCP & Plugins

MCP with stdio Transport

Connect a local MCP server using stdio — the most common transport for local tools

"color:#4B5563"># mcp-config.json
$ {
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@anthropic-ai/mcp-server-filesystem", "/home/user/projects"],
...
2 gotchas
MCP & Plugins

MCP with SSE Transport

Connect to a remote MCP server using Server-Sent Events over HTTP

"color:#4B5563"># mcp-config.json
$ {
"mcpServers": {
"remote-tools": {
"url": "http://internal-tools.company.com:3000/sse"
},
...
2 gotchas
MCP & Plugins

Debug MCP Connections

Diagnose and fix MCP server connection failures using init events and manual testing

"color:#4B5563"># 1. Check init event for server status:
$ claude -p "List tools" "color:#7C5CFC">--output-format stream-json "color:#7C5CFC">--verbose \
"color:#7C5CFC">--mcp-config ./mcp.json | head -1 | jq '.mcp_servers'
"color:#4B5563"># 2. Test server manually:
$ echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{}}}' | \
...
2 gotchas
MCP & Plugins

Install a Plugin

Install and use a plugin from the marketplace or load from a local directory

"color:#4B5563"># From marketplace (inside a session):
$ /plugin install @anthropic/code-review
"color:#4B5563"># From local directory:
$ claude "color:#7C5CFC">--plugin-dir ./my-plugin
...
2 gotchas
MCP & Plugins

Create a Plugin

Build a reusable plugin with skills, agents, hooks, and MCP servers

"color:#4B5563"># Plugin directory structure:
$ my-plugin/
├── .claude-plugin/
│ └── plugin.json "color:#4B5563"># Required manifest
├── skills/
│ └── code-review/
...
2 gotchas
MCP & Plugins

Plugin Hooks

Add lifecycle hooks to a plugin — restricted to http and prompt types for security

"color:#4B5563"># hooks/hooks.json (at plugin root)
$ {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "prompt",
...
2 gotchas
Agents & Orchestration8
Agents & Orchestration

MAX_THINKING_TOKENS Tuning

Cap extended thinking token budget for predictable CI costs

$ MAX_THINKING_TOKENS=8000 claude -p "Refactor auth.py" "color:#7C5CFC">--output-format json
2 gotchas
Agents & Orchestration

Multi-Agent with Worktrees

Run parallel Claude sessions in isolated git worktrees to avoid file conflicts

"color:#4B5563"># Create worktree and run Claude in tmux
$ claude "color:#7C5CFC">--worktree feature-auth "color:#7C5CFC">--tmux
"color:#4B5563"># In another terminal:
$ claude "color:#7C5CFC">--worktree feature-api "color:#7C5CFC">--tmux
2 gotchas
Agents & Orchestration

Create a Custom Agent

Define a specialized agent with custom system prompt, tools, model, and permissions

"color:#4B5563"># .claude/agents/code-reviewer.md
$ "color:#7C5CFC">---
name: code-reviewer
description: Expert code review specialist
tools: Read, Grep, Glob, Bash
model: sonnet
...
2 gotchas
Agents & Orchestration

Agent with Hooks

Attach lifecycle hooks to a custom agent for quality gates and validation

"color:#4B5563"># .claude/agents/safe-coder.md
$ "color:#7C5CFC">---
name: safe-coder
description: Coder with safety hooks
tools: Read, Grep, Glob, Bash, Write, Edit
hooks:
...
2 gotchas
Agents & Orchestration

Parallel File Processing

Process files concurrently using subagents that work in their own context windows

"color:#4B5563"># Agent teams (experimental):
$ CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 claude
"color:#4B5563"># Then describe the team:
$ "I need 3 teammates:
1. Frontend dev for src/components/
...
2 gotchas
Agents & Orchestration

Pipeline Orchestration

Build an HTTP API → Queue → Worker pipeline with Claude CLI as the agent runtime

"color:#4B5563"># Architecture:
"color:#4B5563"># Client → HTTP API → Queue → Worker → claude -p → Parse → Return
"color:#4B5563"># ↓
"color:#4B5563"># Session Store
$
"color:#4B5563"># Simplest backend call:
...
2 gotchas
Agents & Orchestration

Context Management (Compaction)

Manage the 200K token context window with manual and auto compaction

"color:#4B5563"># Inside an interactive session:
$ /compact Focus on API design decisions and test results
"color:#4B5563"># Check what's consuming context:
$ /context
...
2 gotchas
Agents & Orchestration

Proactive Compaction

Compact at ~60% utilization with focus instructions to control what details are preserved

"color:#4B5563"># At ~60% context utilization, compact with focus:
$ /compact Focus on database schema changes and migration decisions
"color:#4B5563"># Or embed in CLAUDE.md for automatic focus:
"color:#4B5563"># Compact instructions
$ When you are using compact, please focus on test output and code changes
2 gotchas
Cost & Performance8
Cost & Performance

Effort Levels Comparison

Control reasoning depth with --effort: low for speed, max for thoroughness

$ claude -p "What is 2+2?" "color:#7C5CFC">--effort low "color:#7C5CFC">--output-format json
2 gotchas
Cost & Performance

Budget Cap Behavior

Understand how --max-budget-usd works: checked between turns, not mid-generation

"color:#4B5563"># This $0.001 budget will be overshot:
$ claude -p "Write a detailed essay" "color:#7C5CFC">--output-format json "color:#7C5CFC">--max-budget-usd 0.001
"color:#4B5563"># Result: $0.152 actual spend (152x overshoot!)
2 gotchas
Cost & Performance

Cap Turns for Safety

Limit agentic conversation turns with --max-turns to prevent runaway loops in automation

$ claude -p "Refactor auth.py to use JWT" \
"color:#7C5CFC">--max-turns 10 \
"color:#7C5CFC">--max-budget-usd 2.00 \
"color:#7C5CFC">--output-format json
3 gotchas
Cost & Performance

Cache Economics Explained

Understand prompt caching tiers and their 90% savings on repeated content

"color:#4B5563"># First call: pays cache write cost
$ claude -p "Hello" "color:#7C5CFC">--output-format json
"color:#4B5563"># Subsequent calls within 5 min: 90% savings on cached content
$ claude -p "Hello again" "color:#7C5CFC">--output-format json
2 gotchas
Cost & Performance

Sonnet vs Opus Decision

Choose the right model: Sonnet is 5x cheaper, Opus is for complex reasoning

"color:#4B5563"># Sonnet for simple tasks:
$ claude -p "Format this JSON" "color:#7C5CFC">--model claude-sonnet-4-6
"color:#4B5563"># Opus for complex reasoning (default):
$ claude -p "Debug this race condition" "color:#7C5CFC">--output-format json
2 gotchas
Cost & Performance

Track Cost Per Call

Extract cost and token breakdown from every JSON response for billing and monitoring

$ RESULT=$(claude -p "What is 2+2?" "color:#7C5CFC">--output-format json)
echo "$RESULT" | jq '{
cost: .total_cost_usd,
input: .usage.input_tokens,
output: .usage.output_tokens,
cached: .usage.cache_read_input_tokens
...
2 gotchas
Cost & Performance

Minimize System Prompt Tokens

Reduce MCP overhead and context consumption to maximize the effective 200K window

"color:#4B5563"># Audit context usage:
$ /context
"color:#4B5563"># Set ToolSearch threshold lower:
$ ENABLE_TOOL_SEARCH=auto:5 claude
...
2 gotchas
Cost & Performance

Batch for Cache Hits

Run similar prompts back-to-back with identical system prompts to maximize cache savings

"color:#4B5563"># Same system prompt across all calls = cache hits
$ for item in "$@"; do
claude -p "Analyze: $item" \
"color:#7C5CFC">--system-prompt "You are a code review assistant." \
"color:#7C5CFC">--output-format json \
"color:#7C5CFC">--no-session-persistence \
...
2 gotchas