Advanced
无头模式自动化
使用 Claude Code 无头模式实现基础设施自动化
Claude Code 包含无头模式,可用于 CI、预提交钩子、构建脚本和自动化等非交互式上下文。
快速结论
用 claude -p 做一次性分析、CI 摘要、Issue triage 或只读 code review。自动化里不要默认给写权限;先让 Claude 输出证据,再由交互式会话或人工决定是否修改。
claude -p "Review the current git diff for bugs, regressions, and missing tests. Return findings with file paths and line references. Do not edit files." \
--allowedTools "Read,Bash(git diff:*)"什么是无头模式
无头模式允许您以编程方式使用 Claude Code,而无需交互式界面。使用 -p 标志与提示词来启用无头模式。
基本用法
claude -p "分析当前项目的代码质量并生成报告"常用参数
--output-format stream-json- 流式JSON输出--allowedTools- 指定允许的工具--verbose- 详细输出用于调试
应用场景
1. 问题分类
无头模式可以支持由GitHub事件触发的自动化:
claude -p "分析这个GitHub Issue并添加适当的标签" \
--allowedTools "Read,Bash(gh:*)"2. 代码检查
超出传统工具检测范围的主观代码审查:
claude -p "Review the current git diff for bugs, regressions, and missing tests. Return findings with file paths and line references. Do not edit files." \
--allowedTools "Read,Bash(git diff:*)"如果搜索意图是 Claude Code review,第一轮应该只读。让 Claude 给出文件、行号、证据和风险;是否修复,放到下一轮交互式会话决定。
| Review 目标 | 更好的 prompt 形态 | 工具边界 |
|---|---|---|
| PR 风险扫描 | Review diff for bugs and regressions. | Read,Bash(git diff:*) |
| Release note 检查 | Summarize user-visible changes and missing migration notes. | Read,Bash(git log:*) |
| 安全敏感 review | 只列有证据的问题,不直接 patch。 | 第一轮只读。 |
3. 批量处理
处理大型迁移或分析任务:
# 生成任务列表
claude -p "生成需要从React迁移到Vue的文件列表"
# 循环处理
for file in $(cat migration-list.txt); do
claude -p "将 $file 从React迁移到Vue" \
--allowedTools "Edit,Bash(git commit:*)"
done注意事项
- 无头模式不在会话间持续,每次都需要重新启动
- 使用
--verbose进行调试,生产环境建议关闭 - 确保网络连接稳定
相关阅读: 多Claude协作 - 学习并行协作工作流程。