claude-headless-mode

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Claude Headless Mode

Claude 无头模式

Use
claude -p
(or
--print
) for non-interactive execution in scripts, CI, and automation.
使用
claude -p
(或
--print
)参数可在脚本、CI、自动化场景中执行非交互式命令。

Basic Usage

基础用法

bash
undefined
bash
undefined

Simple prompt

简单提示词

claude -p "Summarize this repo"
claude -p "Summarize this repo"

With file input

带文件输入

claude -p "Review this code" < file.py
claude -p "Review this code" < file.py

Pipe output

管道输出

claude -p "List all functions" | grep "def "
undefined
claude -p "List all functions" | grep "def "
undefined

Output Formats

输出格式

FormatFlagUse Case
Text
--output-format text
Human-readable (default)
JSON
--output-format json
Single JSON result
Stream JSON
--output-format stream-json --verbose
Real-time streaming
格式参数使用场景
文本
--output-format text
人类可读格式(默认)
JSON
--output-format json
单JSON结果输出
流式JSON
--output-format stream-json --verbose
实时流输出

Text Output (Default)

文本输出(默认)

bash
claude -p "What is 2+2?"
bash
claude -p "What is 2+2?"

Output: 4

输出: 4

undefined
undefined

JSON Output

JSON输出

bash
claude -p "What is 2+2?" --output-format json
Returns wrapper with metadata:
json
{
  "type": "result",
  "subtype": "success",
  "result": "4",
  "duration_ms": 1234,
  "total_cost_usd": 0.01,
  "session_id": "...",
  "structured_output": null
}
Extract just the result:
bash
claude -p "What is 2+2?" --output-format json | jq -r '.result'
bash
claude -p "What is 2+2?" --output-format json
返回带元数据的封装结果:
json
{
  "type": "result",
  "subtype": "success",
  "result": "4",
  "duration_ms": 1234,
  "total_cost_usd": 0.01,
  "session_id": "...",
  "structured_output": null
}
仅提取结果:
bash
claude -p "What is 2+2?" --output-format json | jq -r '.result'

Stream JSON Output

流式JSON输出

bash
claude -p "Long analysis" --output-format stream-json --verbose
  • Streams newline-delimited JSON as execution progresses
  • Shows tool calls, messages, progress in real-time
  • Final line contains the result
  • Requires
    --verbose
    flag
Extract final result:
bash
claude -p "Analyze code" --output-format stream-json --verbose \
  | tee /dev/stderr \
  | tail -1 \
  | jq -r '.result'
bash
claude -p "Long analysis" --output-format stream-json --verbose
  • 执行过程中按换行分隔流式输出JSON
  • 实时展示工具调用、消息、进度信息
  • 最后一行包含最终结果
  • 必须搭配
    --verbose
    参数使用
提取最终结果:
bash
claude -p "Analyze code" --output-format stream-json --verbose \
  | tee /dev/stderr \
  | tail -1 \
  | jq -r '.result'

Structured Output with JSON Schema

基于JSON Schema的结构化输出

Force Claude to return data matching a specific schema:
bash
claude -p "Extract function names from auth.py" \
  --output-format json \
  --json-schema '{
    "type": "object",
    "properties": {
      "functions": { "type": "array", "items": { "type": "string" } }
    },
    "required": ["functions"]
  }'
Result appears in
structured_output
field:
json
{
  "result": "...",
  "structured_output": {
    "functions": ["login", "logout", "verify_token"]
  }
}
强制Claude返回符合指定schema的数据:
bash
claude -p "Extract function names from auth.py" \
  --output-format json \
  --json-schema '{
    "type": "object",
    "properties": {
      "functions": { "type": "array", "items": { "type": "string" } }
    },
    "required": ["functions"]
  }'
结果会出现在
structured_output
字段中:
json
{
  "result": "...",
  "structured_output": {
    "functions": ["login", "logout", "verify_token"]
  }
}

Schema Examples

Schema示例

Simple object:
json
{
  "type": "object",
  "properties": {
    "answer": { "type": "integer" }
  },
  "required": ["answer"]
}
Task result (success/failure):
json
{
  "type": "object",
  "properties": {
    "status": { "type": "string", "enum": ["success", "failure"] },
    "summary": { "type": "string" },
    "files_changed": { "type": "array", "items": { "type": "string" } },
    "error_category": { "type": "string" },
    "suggestion": { "type": "string" }
  },
  "required": ["status", "summary"]
}
Extract from schema result:
bash
OUTPUT=$(claude -p "$PROMPT" --output-format json --json-schema "$SCHEMA")
STATUS=$(echo "$OUTPUT" | jq -r '.structured_output.status')
SUMMARY=$(echo "$OUTPUT" | jq -r '.structured_output.summary')
简单对象:
json
{
  "type": "object",
  "properties": {
    "answer": { "type": "integer" }
  },
  "required": ["answer"]
}
任务结果(成功/失败):
json
{
  "type": "object",
  "properties": {
    "status": { "type": "string", "enum": ["success", "failure"] },
    "summary": { "type": "string" },
    "files_changed": { "type": "array", "items": { "type": "string" } },
    "error_category": { "type": "string" },
    "suggestion": { "type": "string" }
  },
  "required": ["status", "summary"]
}
从schema结果中提取数据:
bash
OUTPUT=$(claude -p "$PROMPT" --output-format json --json-schema "$SCHEMA")
STATUS=$(echo "$OUTPUT" | jq -r '.structured_output.status')
SUMMARY=$(echo "$OUTPUT" | jq -r '.structured_output.summary')

Common Options

常用选项

OptionDescription
-p, --print
Headless mode (required)
--output-format
text, json, stream-json
--json-schema
Enforce output schema
--verbose
Required for stream-json
--model
Select model (sonnet, opus, haiku)
--max-turns
Limit agentic turns
--permission-mode
bypassPermissions, plan, etc.
--allowedTools
Restrict available tools
选项描述
-p, --print
无头模式(必填)
--output-format
可选值:text, json, stream-json
--json-schema
强制输出符合指定schema
--verbose
stream-json模式必填
--model
选择模型(sonnet, opus, haiku)
--max-turns
限制agent交互轮次
--permission-mode
可选值:bypassPermissions, plan等
--allowedTools
限制可用工具范围

Permission Modes

权限模式

bash
undefined
bash
undefined

Skip all permission prompts (trusted environments only)

跳过所有权限确认提示(仅可在可信环境中使用)

claude -p "Fix all linting errors" --permission-mode bypassPermissions
claude -p "Fix all linting errors" --permission-mode bypassPermissions

Plan mode (read-only exploration)

计划模式(只读探索)

claude -p "Analyze architecture" --permission-mode plan
undefined
claude -p "Analyze architecture" --permission-mode plan
undefined

Examples

示例

CI/CD Integration

CI/CD集成

bash
undefined
bash
undefined

Run tests and get structured result

运行测试并获取结构化结果

RESULT=$(claude -p "Run tests and report results"
--output-format json
--json-schema '{"type":"object","properties":{"passed":{"type":"boolean"},"failures":{"type":"array","items":{"type":"string"}}},"required":["passed"]}')
if [ "$(echo $RESULT | jq '.structured_output.passed')" = "true" ]; then echo "Tests passed" else echo "Tests failed" exit 1 fi
undefined
RESULT=$(claude -p "Run tests and report results"
--output-format json
--json-schema '{"type":"object","properties":{"passed":{"type":"boolean"},"failures":{"type":"array","items":{"type":"string"}}},"required":["passed"]}')
if [ "$(echo $RESULT | jq '.structured_output.passed')" = "true" ]; then echo "Tests passed" else echo "Tests failed" exit 1 fi
undefined

Batch Processing

批处理

bash
for file in src/*.py; do
  claude -p "Review $file for security issues" \
    --output-format json \
    --json-schema '{"type":"object","properties":{"issues":{"type":"array"}},"required":["issues"]}' \
    | jq ".structured_output.issues"
done
bash
for file in src/*.py; do
  claude -p "Review $file for security issues" \
    --output-format json \
    --json-schema '{"type":"object","properties":{"issues":{"type":"array"}},"required":["issues"]}' \
    | jq ".structured_output.issues"
done

Fresh Context Task Execution

新上下文任务执行

bash
undefined
bash
undefined

Each invocation is independent (no conversation history)

每次调用都是独立的(无对话历史)

claude -p "Task 1: Create migration" --output-format json claude -p "Task 2: Add model" --output-format json claude -p "Task 3: Write tests" --output-format json
undefined
claude -p "Task 1: Create migration" --output-format json claude -p "Task 2: Add model" --output-format json claude -p "Task 3: Write tests" --output-format json
undefined

Task Coordination

任务协调

Share TaskList across headless invocations using
CLAUDE_CODE_TASK_LIST_ID
.
通过
CLAUDE_CODE_TASK_LIST_ID
在多个无头模式调用之间共享任务列表。

Environment Variable

环境变量

bash
undefined
bash
undefined

All invocations share the same TaskList

所有调用共享同一个任务列表

export CLAUDE_CODE_TASK_LIST_ID="my-project" claude -p "Use TaskCreate to add: Setup database" claude -p "Use TaskCreate to add: Write migrations" claude -p "Use TaskList to show all tasks" # Shows both tasks
undefined
export CLAUDE_CODE_TASK_LIST_ID="my-project" claude -p "Use TaskCreate to add: Setup database" claude -p "Use TaskCreate to add: Write migrations" claude -p "Use TaskList to show all tasks" # 会展示上述两个任务
undefined

Pattern: Orchestrator + Workers

模式:编排器 + 工作器

bash
TASK_LIST_ID="epic-$(date +%Y%m%d)"
export CLAUDE_CODE_TASK_LIST_ID="$TASK_LIST_ID"
bash
TASK_LIST_ID="epic-$(date +%Y%m%d)"
export CLAUDE_CODE_TASK_LIST_ID="$TASK_LIST_ID"

Orchestrator creates tasks

编排器创建任务

claude -p "Use TaskCreate for each: Task 1, Task 2, Task 3"
claude -p "Use TaskCreate for each: Task 1, Task 2, Task 3"

Workers execute (each sees shared TaskList)

工作器执行任务(每个工作器都能看到共享的任务列表)

for task_id in 1 2 3; do claude -p "Use TaskUpdate to mark task #$task_id as in_progress, implement it, then mark completed" done
for task_id in 1 2 3; do claude -p "Use TaskUpdate to mark task #$task_id as in_progress, implement it, then mark completed" done

Check final state

检查最终状态

claude -p "Use TaskList to show status"
undefined
claude -p "Use TaskList to show status"
undefined

Task Tools

任务工具

ToolPurpose
TaskCreate
Create new task with subject, description
TaskList
List all tasks with status
TaskUpdate
Update task status (in_progress, completed) or add blockedBy
TaskGet
Get full details of a specific task
工具用途
TaskCreate
创建带主题、描述的新任务
TaskList
列出所有任务及状态
TaskUpdate
更新任务状态(进行中、已完成)或添加阻塞依赖
TaskGet
获取指定任务的完整详情

Dependencies

依赖关系

bash
undefined
bash
undefined

Task 2 depends on Task 1

任务2依赖任务1

claude -p "Use TaskUpdate on task #2 to set blockedBy: [1]"

Tasks persist to `~/.claude/tasks/` and survive session restarts.
claude -p "Use TaskUpdate on task #2 to set blockedBy: [1]"

任务会持久化存储到`~/.claude/tasks/`,会话重启后仍然存在。

Notes

注意事项

  • Each
    -p
    invocation starts fresh (no context from previous runs)
  • Use
    --output-format json
    for programmatic parsing
  • structured_output
    field contains schema-validated data
  • result
    field contains raw text response
  • Stream JSON requires
    --verbose
    flag
  • Cost info available in JSON output:
    total_cost_usd
  • 每次
    -p
    调用都是全新上下文(无之前运行的上下文)
  • 如需程序解析请使用
    --output-format json
  • structured_output
    字段包含经过schema校验的数据
  • result
    字段包含原始文本响应
  • 流式JSON输出需要搭配
    --verbose
    参数
  • 成本信息可在JSON输出的
    total_cost_usd
    字段中获取