claude-headless-mode
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseClaude Headless Mode
Claude 无头模式
Use (or ) for non-interactive execution in scripts, CI, and automation.
claude -p--print使用(或)参数可在脚本、CI、自动化场景中执行非交互式命令。
claude -p--printBasic Usage
基础用法
bash
undefinedbash
undefinedSimple 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 "
undefinedclaude -p "List all functions" | grep "def "
undefinedOutput Formats
输出格式
| Format | Flag | Use Case |
|---|---|---|
| Text | | Human-readable (default) |
| JSON | | Single JSON result |
| Stream JSON | | Real-time streaming |
| 格式 | 参数 | 使用场景 |
|---|---|---|
| 文本 | | 人类可读格式(默认) |
| JSON | | 单JSON结果输出 |
| 流式JSON | | 实时流输出 |
Text Output (Default)
文本输出(默认)
bash
claude -p "What is 2+2?"bash
claude -p "What is 2+2?"Output: 4
输出: 4
undefinedundefinedJSON Output
JSON输出
bash
claude -p "What is 2+2?" --output-format jsonReturns 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 flag
--verbose
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 field:
structured_outputjson
{
"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_outputjson
{
"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
常用选项
| Option | Description |
|---|---|
| Headless mode (required) |
| text, json, stream-json |
| Enforce output schema |
| Required for stream-json |
| Select model (sonnet, opus, haiku) |
| Limit agentic turns |
| bypassPermissions, plan, etc. |
| Restrict available tools |
| 选项 | 描述 |
|---|---|
| 无头模式(必填) |
| 可选值:text, json, stream-json |
| 强制输出符合指定schema |
| stream-json模式必填 |
| 选择模型(sonnet, opus, haiku) |
| 限制agent交互轮次 |
| 可选值:bypassPermissions, plan等 |
| 限制可用工具范围 |
Permission Modes
权限模式
bash
undefinedbash
undefinedSkip 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
undefinedclaude -p "Analyze architecture" --permission-mode plan
undefinedExamples
示例
CI/CD Integration
CI/CD集成
bash
undefinedbash
undefinedRun 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"]}')
--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
undefinedRESULT=$(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"]}')
--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
undefinedBatch 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"
donebash
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"
doneFresh Context Task Execution
新上下文任务执行
bash
undefinedbash
undefinedEach 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
undefinedclaude -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
undefinedTask Coordination
任务协调
Share TaskList across headless invocations using .
CLAUDE_CODE_TASK_LIST_ID通过在多个无头模式调用之间共享任务列表。
CLAUDE_CODE_TASK_LIST_IDEnvironment Variable
环境变量
bash
undefinedbash
undefinedAll 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
undefinedexport 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" # 会展示上述两个任务
undefinedPattern: 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"
undefinedclaude -p "Use TaskList to show status"
undefinedTask Tools
任务工具
| Tool | Purpose |
|---|---|
| Create new task with subject, description |
| List all tasks with status |
| Update task status (in_progress, completed) or add blockedBy |
| Get full details of a specific task |
| 工具 | 用途 |
|---|---|
| 创建带主题、描述的新任务 |
| 列出所有任务及状态 |
| 更新任务状态(进行中、已完成)或添加阻塞依赖 |
| 获取指定任务的完整详情 |
Dependencies
依赖关系
bash
undefinedbash
undefinedTask 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 invocation starts fresh (no context from previous runs)
-p - Use for programmatic parsing
--output-format json - field contains schema-validated data
structured_output - field contains raw text response
result - Stream JSON requires flag
--verbose - Cost info available in JSON output:
total_cost_usd
- 每次调用都是全新上下文(无之前运行的上下文)
-p - 如需程序解析请使用
--output-format json - 字段包含经过schema校验的数据
structured_output - 字段包含原始文本响应
result - 流式JSON输出需要搭配参数
--verbose - 成本信息可在JSON输出的字段中获取
total_cost_usd