Headless 模式
用 claude -p 在脚本、CI 和自动化里非交互式运行 Claude Code,包括 bare mode、结构化输出、工具授权和继续会话。
Headless 模式指不进入交互式 TUI,而是让 Claude Code 接收一个 prompt、执行任务、把结果打印到 stdout。命令行入口是 claude -p 或 claude --print,适合脚本、CI、review bot 和一次性自动化。
如果要把 headless 用在 GitHub Actions、GitLab CI、官方 Code Review 或云端 review 旁边比较,看 平台与集成。
如果只是写脚本调用 CLI,用 claude -p 就够。要在产品里管理消息对象、审批回调、结构化事件和长期 agent,优先看 Agent SDK。
#最小用法
claude -p "What does the auth module do?"常见组合:
| 命令 | 用途 |
|---|---|
claude -p "总结当前项目" | 执行一次并输出文本 |
claude -p "解释这个错误" < build.log | 从 stdin 读取日志或文本 |
claude -p "继续分析数据库查询" --continue | 继续当前目录最近会话 |
claude -p "继续审查" --resume "$session_id" | 恢复指定 session |
claude -p "运行测试并修复失败" --allowedTools "Bash,Read,Edit" | 预批准工具 |
claude -p "总结项目" --output-format json | 输出 JSON 结果和元数据 |
-p 可以配合常规 CLI flags 使用,例如 --model、--settings、--mcp-config、--append-system-prompt、--allowedTools、--output-format 和 --json-schema。
#推荐脚本使用 --bare
--bare 会跳过自动发现 Hooks、Skills、Plugins、MCP servers、auto memory 和 CLAUDE.md,只使用你显式传入的参数。它更快,也更适合 CI,因为同一条脚本不会受同事机器上的 ~/.claude 配置影响。
claude --bare -p "Summarize this file" --allowedTools "Read"在 bare mode 中,Claude 仍可使用 Bash、文件读取和文件编辑工具。需要额外上下文时,用参数显式传入:
| 要加载 | 使用 |
|---|---|
| 系统提示追加 | --append-system-prompt、--append-system-prompt-file |
| settings | --settings <file-or-json> |
| MCP servers | --mcp-config <file-or-json> |
| custom agents | --agents <json> |
| plugin | --plugin-dir <path>、--plugin-url <url> |
官方说明中,--bare 会跳过 OAuth 和 keychain 读取。接入 Passion8 时,不要依赖交互式登录状态;在运行环境里显式提供 ANTHROPIC_BASE_URL=https://passion8.cc 和 ANTHROPIC_AUTH_TOKEN,或通过 --settings 传入对应配置。
官方也说明 --bare 是脚本和 SDK 调用的推荐模式,未来会成为 -p 的默认行为。现在写自动化时建议直接加上,避免之后行为迁移。
#Pipe 输入和输出
Headless 模式会读取 stdin,所以可以像普通 Unix 工具一样串管道:
cat build-error.txt | claude --bare -p "简洁解释这个构建错误的根因" > output.txt从 Claude Code v2.1.128 起,piped stdin 上限为 10MB。超过后会清晰报错并返回非零状态。更大的输入先写成文件,再在 prompt 里引用路径。
在 package.json 里也可以把 Claude 当作项目级检查器:
{
"scripts": {
"lint:claude": "git diff main | claude --bare -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\""
}
}把 diff 通过 stdin 传入时,Claude 不需要 Bash 权限去读取 Git diff。
#结构化输出
--output-format 控制返回格式:
| 格式 | 说明 |
|---|---|
text | 默认,只打印最终文本 |
json | 返回 result、session_id、usage、成本等元数据 |
stream-json | 按行输出 JSON event,适合实时 UI 或日志系统 |
普通 JSON:
claude --bare -p "Summarize this project" --output-format json用 JSON Schema 约束结构化结果:
claude --bare -p "Extract the main function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'JSON 输出里,自然语言结果在 result 字段;使用 --json-schema 时,结构化结果在 structured_output 字段。脚本里通常配合 jq:
claude --bare -p "Summarize this project" --output-format json | jq -r '.result'#流式事件
实时流式输出使用:
claude --bare -p "Explain recursion" \
--output-format stream-json \
--verbose \
--include-partial-messages常见事件:
| 事件 | 用途 |
|---|---|
system/init | 报告 session、model、tools、MCP servers、loaded plugins 等初始化信息 |
system/api_retry | API 请求遇到可重试错误时输出重试次数、延迟和错误类别 |
system/plugin_install | 设置 CLAUDE_CODE_SYNC_PLUGIN_INSTALL 时,报告 marketplace plugin 安装进度 |
stream_event | 模型输出、工具调用等流式消息 |
只显示文本增量可以用:
claude --bare -p "Write a short release note" --output-format stream-json --verbose --include-partial-messages | \
jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'#工具授权和权限模式
--allowedTools 是“预批准工具”,不是“限制工具列表”。如果要做锁定式 CI,把它和权限模式一起用。
| 配置 | 行为 |
|---|---|
--allowedTools "Read,Edit,Bash" | 这些工具需要时不再交互确认 |
--permission-mode dontAsk | 未被权限规则允许的动作直接拒绝 |
--permission-mode acceptEdits | 文件编辑和常见文件系统命令自动接受 |
permissions.allow | 用 settings 精确允许命令、路径或 MCP 工具 |
示例:
claude --bare -p "Run the test suite and fix failures" \
--allowedTools "Bash,Read,Edit" \
--permission-mode acceptEdits自动提交这类任务应收窄 Bash 规则:
claude --bare -p "Review staged changes and create a commit" \
--allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"权限规则里的空格很重要:Bash(git diff *) 匹配 git diff ...,Bash(git diff*) 可能匹配到更宽的命令前缀。
#自定义系统提示
想保留 Claude Code 默认行为,只追加角色或检查重点,用 --append-system-prompt:
gh pr diff "$1" | claude --bare -p \
--append-system-prompt "You are a security engineer. Review for vulnerabilities." \
--output-format json--system-prompt 会替换默认系统提示,除非你明确知道要完整接管 agent 行为,否则更推荐追加。
#继续会话
claude -p 也可以多轮继续:
claude --bare -p "Review this codebase for performance issues"
claude --bare -p "Now focus on database queries" --continue
claude --bare -p "Generate a summary of all issues found" --continue需要精确恢复某条会话时,先保存 session ID:
session_id=$(claude --bare -p "Start a review" --output-format json | jq -r '.session_id')
claude --bare -p "Continue that review" --resume "$session_id"从同一个目录运行这些命令。官方说明里,session ID 查找会按当前项目目录和 Git worktree 作用域解析。
#后台任务退出行为
如果 claude -p 期间启动了后台 Bash 任务,例如 dev server 或 watch build,Claude 返回最终结果且 stdin 关闭后,该 shell 大约 5 秒后会被终止。这个宽限期允许刚好结束的任务吐完输出。
后台 subagents 和 workflows 不受这 5 秒规则影响,因为它们的结果属于最终输出。Claude Code 会等待它们完成;从 v2.1.182 起,默认最多等待 10 分钟。可用 CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS 调整,设置为 0 表示不设上限。
#命令和 Skills
用户触发的 Skills 和自定义命令可在 -p prompt 里直接写:
claude -p "/my-skill 检查这个模块的发布风险"如果脚本使用 --bare,Claude Code 不会自动发现本机的 Skills、Plugins 和自定义扩展。需要这类能力时,不要用 bare mode,或用 --plugin-dir、--plugin-url 等参数显式加载。
会打开交互式 UI 的内置命令不适合 headless,例如 /login。需要从 -p 临时改配置时,可在 prompt 中用 /config key=value 这类形式。
#官方参考
Support / 支持
Need help? / 需要帮助?
接入、计费与模型异常可邮件联系;服务可用性以状态页为准。
For setup, billing, or model issues, email us. Check the status page for uptime.
也可使用右下角微信 / QQ 客服 · WeChat / QQ support is available at the bottom right

