Claude Code 不只是交互式工具,它的非交互(Headless)模式让你可以将 AI 编程能力嵌入到 Shell 脚本、CI/CD 流水线、自动化工具和批量处理任务中。本文全面介绍 Headless 模式的使用场景和技巧。
什么是 Headless 模式?
Headless 模式通过 -p(--print)标志启用,让 Claude Code 以非交互方式执行单个任务并输出结果,然后退出。这与交互式的对话模式完全不同。
bash
# 基本用法
claude -p "your prompt here"
# 从标准输入读取提示词
echo "analyze this code" | claude -p -
# 读取文件内容作为输入
claude -p "review this" < myfile.ts常用参数
| 参数 | 说明 |
|---|---|
-p / --print | 非交互模式,打印响应后退出 |
--model <alias> | 指定模型 |
--permission-mode <mode> | 权限模式(plan/acceptEdits/bypassPermissions) |
--max-turns <n> | 限制最大对话轮次 |
--output-format <format> | 输出格式(text/json/stream-json) |
--allowedTools <tools> | 限制可用工具(逗号分隔) |
--disallowedTools <tools> | 禁止特定工具 |
--append-system-prompt <text> | 追加系统提示词 |
--add-dir <path> | 添加额外工作目录 |
--no-auto-approve | 禁止自动批准(交互模式使用) |
实用场景示例
1. 代码审查脚本
bash
#!/bin/bash
# 审查最近的 git 变更
git diff HEAD~1 | claude -p "Review these changes for security vulnerabilities and code quality issues. Be concise."2. 自动生成 Commit 信息
bash
#!/bin/bash
# 基于 diff 生成 Conventional Commit 格式的提交信息
COMMIT_MSG=$(git diff --staged | claude -p "
Generate a git commit message for these staged changes.
Follow Conventional Commits format: <type>(<scope>): <description>
Types: feat, fix, docs, style, refactor, test, chore
Be concise, no more than 72 characters for the first line.
Output ONLY the commit message, nothing else.
")
echo "Suggested commit message: $COMMIT_MSG"
read -p "Use this message? [y/N] " confirm
if [[ "$confirm" == [yY] ]]; then
git commit -m "$COMMIT_MSG"
fi3. 批量文档生成
bash
#!/bin/bash
# 为所有缺少 JSDoc 的函数生成文档
for file in src/**/*.ts; do
echo "Processing $file..."
claude -p "Add JSDoc comments to any exported functions in this file that are missing documentation. Only output the modified file content." < "$file" > "$file.new"
mv "$file.new" "$file"
done
echo "Documentation generation complete!"4. CI/CD 代码审查(GitHub Actions)
yaml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Claude Code
run: curl -fsSL https://claude.ai/install.sh | bash
- name: Review PR Changes
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
git diff origin/main...HEAD | claude -p "
Review these PR changes. Check for:
1. Security vulnerabilities
2. Performance issues
3. Missing error handling
4. Breaking changes
Format as a concise list. Use ✅ for looks good, ⚠️ for suggestions, ❌ for issues.
" > review.txt
cat review.txt
- name: Post Review Comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('review.txt', 'utf8');
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: `## 🤖 AI Code Review\n\n${review}`
});5. 数据处理和报告生成
bash
#!/bin/bash
# 分析错误日志并生成摘要报告
tail -n 1000 /var/log/app/error.log | claude -p "
Analyze these error logs and provide:
1. Top 5 most frequent errors (with count)
2. Critical issues requiring immediate attention
3. Suggested fixes for the most common issue
Format as markdown.
" > error_report.md
echo "Error report generated: error_report.md"6. Plan Mode 无交互分析
bash
# 以只读 Plan Mode 分析代码
claude --permission-mode plan -p "Analyze the authentication system for potential security improvements. Do not make any changes."7. 结构化 JSON 输出
bash
# 获取 JSON 格式的分析结果,方便脚本处理
RESULT=$(claude -p "Analyze the package.json and return a JSON object with keys: hasTests, hasCI, hasDependencyLock, securityIssues (array)" \
--output-format json < package.json)
echo "$RESULT" | jq '.securityIssues[]'权限模式选择
非交互模式下的权限模式选择:
bash
# Plan Mode(只读,安全)- 适合 CI 代码审查
claude --permission-mode plan -p "Analyze this PR for issues"
# acceptEdits(自动接受文件修改)- 适合自动化代码生成
claude --permission-mode acceptEdits -p "Add JSDoc to all functions"
# bypassPermissions(跳过所有确认)- 仅在完全受控环境使用!
claude --permission-mode bypassPermissions -p "Refactor the auth module"⚠️
bypassPermissions跳过所有安全检查,仅在你完全信任运行环境时使用,通常只适合专用的 CI/CD 沙箱环境。
限制工具访问
bash
# 只允许读取工具(最安全)
claude --permission-mode plan \
--allowedTools "Read,Bash(git log *),Bash(git diff *)" \
-p "Review the last 5 commits for any security concerns"
# 禁止网络访问
claude --disallowedTools "Bash(curl *),Bash(wget *),mcp__*" \
-p "Refactor the user service"设置最大轮次
bash
# 防止无限循环
claude --max-turns 10 -p "Fix the failing tests in src/auth/"处理长内容
bash
# 处理大文件:分块处理
for i in $(seq 1 10 100); do
sed -n "${i},$((i+9))p" large-file.ts | \
claude -p "Add TypeScript types to these function signatures"
done
# 或使用 --add-dir 访问整个目录
claude --add-dir /path/to/extra/context \
-p "Analyze the codebase with access to the additional context"最佳实践
- 明确具体的 Prompt:非交互模式下没有机会澄清,确保提示词足够精确
- 设置 max-turns:防止意外的长时间运行
- 使用 Plan Mode 进行审查:只读分析任务始终使用
--permission-mode plan - JSON 输出便于集成:需要解析结果时使用
--output-format json - 测试后再自动化:先在交互模式验证 Prompt,再放入脚本
总结
Headless 模式是 Claude Code 从开发工具升级为自动化平台的关键。将 AI 编程能力嵌入脚本和 CI/CD,可以实现代码审查、文档生成、错误分析等任务的全自动化,真正让 AI 融入工程师的完整工作流。
来源:Claude Code 官方文档 - Headless Mode 原文作者:Anthropic Team