claude-skill

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Claude Code Headless Mode

Claude Code 无头模式

You are operating in Claude Code headless mode - a non-interactive automation mode for hands-off task execution.
您当前处于Claude Code无头模式——一种无需交互的自动化模式,可自动执行任务无需人工介入。

Prerequisites

前提条件

Before using this skill, ensure Claude Code CLI is installed and configured:
  1. Installation verification:
    bash
    claude --version
  2. First-time setup: If not installed, guide the user to install Claude Code CLI with command
    npm install -g @anthropic-ai/claude-code
    .
使用此技能前,请确保已安装并配置Claude Code CLI:
  1. 安装验证
    bash
    claude --version
  2. 首次设置:如果未安装,引导用户使用命令
    npm install -g @anthropic-ai/claude-code
    安装Claude Code CLI。

Core Principles

核心原则

Autonomous Execution

自主执行

  • Execute tasks from start to finish without seeking approval for each action
  • Make confident decisions based on best practices and task requirements
  • Only ask questions if critical information is genuinely missing
  • Prioritize completing the workflow over explaining every step
  • 从头到尾执行任务,无需为每个操作寻求审批
  • 根据最佳实践和任务要求做出可靠决策
  • 仅在确实缺少关键信息时才询问问题
  • 优先完成工作流,而非解释每一步

Output Behavior

输出行为

  • Stream progress updates as you work
  • Provide a clear, structured final summary upon completion
  • Focus on actionable results and metrics over lengthy explanations
  • Report what was done, not what could have been done
  • 执行过程中实时输出进度更新
  • 完成后提供清晰、结构化的最终总结
  • 专注于可操作的结果和指标,而非冗长的解释
  • 报告已完成的工作,而非可能完成的工作

Permission Modes

权限模式

Claude Code uses permission modes to control what operations are permitted. Set via
--permission-mode
flag:
ModeDescription
default
Standard behavior - prompts for permission on first use of each tool
acceptEdits
Automatically accepts file edit permissions for the session (Default for this skill)
plan
Plan Mode - Claude can analyze but not modify files or execute commands
bypassPermissions
Skips all permission prompts (requires safe environment - see warning below)
Accept Edits Mode (
--permission-mode acceptEdits
)
- Default
  • Automatically accepts file edits without prompts
  • Still requires approval for shell commands
  • Recommended for most programming tasks
  • This is the default mode for this skill
Default Mode (
--permission-mode default
)
  • Requires approval for file edits and command execution
  • Safe for exploration and analysis tasks
Plan Mode (
--permission-mode plan
)
  • Read-only analysis mode
  • Claude can explore and analyze but cannot modify files
  • Cannot execute commands
  • Useful for code review and architecture analysis
Bypass Permissions Mode (
--permission-mode bypassPermissions
)
  • Skips ALL permission prompts
  • ⚠️ WARNING: Only use in externally sandboxed environments (containers, VMs)
  • NEVER use on your development machine without proper isolation
  • Use with
    --allowedTools
    to restrict specific tools for safety
Claude Code使用权限模式控制允许的操作,通过
--permission-mode
标志设置:
模式描述
default
标准行为——首次使用每个工具时会提示获取权限
acceptEdits
自动接受会话中的文件编辑权限 (此技能的默认模式)
plan
规划模式——Claude可以分析但不能修改文件或执行命令
bypassPermissions
跳过所有权限提示(需要安全环境——见下方警告)
接受编辑模式 (
--permission-mode acceptEdits
)
- 默认
  • 自动接受文件编辑,无需提示
  • 执行Shell命令仍需审批
  • 推荐用于大多数编程任务
  • 这是此技能的默认模式
默认模式 (
--permission-mode default
)
  • 文件编辑和命令执行都需要审批
  • 适用于探索和分析类任务
规划模式 (
--permission-mode plan
)
  • 只读分析模式
  • Claude可以探索和分析但不能修改文件
  • 无法执行命令
  • 适用于代码审查和架构分析
跳过权限模式 (
--permission-mode bypassPermissions
)
  • 跳过所有权限提示
  • ⚠️ 警告:仅在外部沙箱环境(容器、虚拟机)中使用
  • 切勿在未做适当隔离的开发机器上使用
  • 可配合
    --allowedTools
    限制特定工具以保障安全

Claude Code CLI Commands

Claude Code CLI 命令

Note: The following commands are based on the official Claude Code headless mode documentation.
注意:以下命令基于官方Claude Code无头模式文档。

Basic Headless Execution

基础无头执行

Use the
--print
(or
-p
) flag to run in non-interactive mode:
bash
claude -p "analyze the codebase structure and explain the architecture"
使用
--print
(或
-p
)标志以非交互式模式运行:
bash
claude -p "analyze the codebase structure and explain the architecture"

Tool Permissions

工具权限

Control which tools Claude can use with
--allowedTools
and
--disallowedTools
:
bash
undefined
通过
--allowedTools
--disallowedTools
控制Claude可使用的工具:
bash
undefined

Allow specific tools

允许特定工具

claude -p "stage my changes and write commits"
--allowedTools "Bash,Read"
--permission-mode acceptEdits
claude -p "stage my changes and write commits"
--allowedTools "Bash,Read"
--permission-mode acceptEdits

Allow multiple tools (space-separated)

允许多个工具(空格分隔)

claude -p "implement the feature"
--permission-mode acceptEdits
--allowedTools Bash Read Write Edit
claude -p "implement the feature"
--permission-mode acceptEdits
--allowedTools Bash Read Write Edit

Allow tools with restrictions (comma-separated string)

允许带限制的工具(逗号分隔字符串)

claude -p "run tests"
--permission-mode acceptEdits
--allowedTools "Bash(npm test),Read"
claude -p "run tests"
--permission-mode acceptEdits
--allowedTools "Bash(npm test),Read"

Disallow specific tools

禁止特定工具

claude -p "analyze the code"
--disallowedTools "Bash,Write"
undefined
claude -p "analyze the code"
--disallowedTools "Bash,Write"
undefined

Using Permission Modes

使用权限模式

Control how permissions are handled:
bash
undefined
控制权限处理方式:
bash
undefined

Accept file edits automatically (recommended for programming)

自动接受文件编辑(推荐用于编程任务)

claude -p "implement the user authentication feature"
--permission-mode acceptEdits
--allowedTools "Bash,Read,Write,Edit"
claude -p "implement the user authentication feature"
--permission-mode acceptEdits
--allowedTools "Bash,Read,Write,Edit"

Combine with allowed tools for safe automation

结合允许的工具实现安全自动化

claude -p "fix the bug in login flow"
--permission-mode acceptEdits
--allowedTools "Read,Write,Edit,Bash(npm test)"
undefined
claude -p "fix the bug in login flow"
--permission-mode acceptEdits
--allowedTools "Read,Write,Edit,Bash(npm test)"
undefined

Output Formats

输出格式

Text Output (Default)

文本输出(默认)

bash
claude -p "explain file src/components/Header.tsx"
bash
claude -p "explain file src/components/Header.tsx"

Output: Plain text response

输出:纯文本响应

undefined
undefined

JSON Output

JSON输出

Returns structured data including metadata:
bash
claude -p "how does the data layer work?" --output-format json
Response format:
json
{
  "type": "result",
  "subtype": "success",
  "total_cost_usd": 0.003,
  "is_error": false,
  "duration_ms": 1234,
  "duration_api_ms": 800,
  "num_turns": 6,
  "result": "The response text here...",
  "session_id": "abc123"
}
返回包含元数据的结构化数据:
bash
claude -p "how does the data layer work?" --output-format json
响应格式:
json
{
  "type": "result",
  "subtype": "success",
  "total_cost_usd": 0.003,
  "is_error": false,
  "duration_ms": 1234,
  "duration_api_ms": 800,
  "num_turns": 6,
  "result": "The response text here...",
  "session_id": "abc123"
}

Streaming JSON Output

流式JSON输出

Streams each message as it is received:
bash
claude -p "build an application" \
  --permission-mode acceptEdits \
  --output-format stream-json
Each conversation begins with an initial
init
system message, followed by user and assistant messages, followed by a final
result
system message with stats.
接收消息时实时流式输出:
bash
claude -p "build an application" \
  --permission-mode acceptEdits \
  --output-format stream-json
每个会话以初始
init
系统消息开始,随后是用户和助手消息,最后是包含统计信息的最终
result
系统消息。

Multi-Turn Conversations

多轮对话

For multi-turn conversations, you can resume or continue sessions:
bash
undefined
对于多轮对话,您可以恢复或继续会话:
bash
undefined

Continue the most recent conversation

继续最近的对话

claude --continue --permission-mode acceptEdits "now refactor this for better performance"
claude --continue --permission-mode acceptEdits "now refactor this for better performance"

Resume a specific conversation by session ID

通过会话ID恢复特定对话

claude --resume 550e8400-e29b-41d4-a716-446655440000
--permission-mode acceptEdits "update the tests"
claude --resume 550e8400-e29b-41d4-a716-446655440000
--permission-mode acceptEdits "update the tests"

Resume in non-interactive mode

以非交互式模式恢复

claude --resume 550e8400-e29b-41d4-a716-446655440000 -p
--permission-mode acceptEdits "fix all linting issues"
claude --resume 550e8400-e29b-41d4-a716-446655440000 -p
--permission-mode acceptEdits "fix all linting issues"

Short flags

短标志

claude -c --permission-mode acceptEdits "continue with next step" claude -r abc123 -p --permission-mode acceptEdits "implement the next feature"
undefined
claude -c --permission-mode acceptEdits "continue with next step" claude -r abc123 -p --permission-mode acceptEdits "implement the next feature"
undefined

System Prompt Customization

系统提示自定义

Append custom instructions to the system prompt:
bash
claude -p "review this code" \
  --append-system-prompt "Focus on security vulnerabilities and performance issues"
将自定义指令附加到系统提示:
bash
claude -p "review this code" \
  --append-system-prompt "Focus on security vulnerabilities and performance issues"

MCP Server Configuration

MCP服务器配置

Load MCP servers from a JSON configuration file:
bash
claude -p "analyze the metrics" \
  --mcp-config monitoring-tools.json \
  --allowedTools "mcp__datadog,mcp__prometheus"
从JSON配置文件加载MCP服务器:
bash
claude -p "analyze the metrics" \
  --mcp-config monitoring-tools.json \
  --allowedTools "mcp__datadog,mcp__prometheus"

Verbose Logging

详细日志

Enable verbose output for debugging:
bash
claude -p "debug this issue" --verbose
启用详细输出以进行调试:
bash
claude -p "debug this issue" --verbose

Combined Examples

组合示例

Combine multiple flags for complex scenarios:
bash
undefined
组合多个标志以应对复杂场景:
bash
undefined

Full automation with JSON output

带JSON输出的完整自动化

claude -p "implement authentication and output results"
--permission-mode acceptEdits
--allowedTools "Bash,Read,Write,Edit"
--output-format json
claude -p "implement authentication and output results"
--permission-mode acceptEdits
--allowedTools "Bash,Read,Write,Edit"
--output-format json

Multi-turn with custom instructions

带自定义指令的多轮对话

session_id=$(claude -p "start code review" --output-format json | jq -r '.session_id') claude -r "$session_id" -p "now check for security issues"
--permission-mode acceptEdits
--append-system-prompt "Be thorough with OWASP top 10"
session_id=$(claude -p "start code review" --output-format json | jq -r '.session_id') claude -r "$session_id" -p "now check for security issues"
--permission-mode acceptEdits
--append-system-prompt "Be thorough with OWASP top 10"

Streaming with MCP tools

带MCP工具的流式输出

claude -p "deploy the application"
--permission-mode acceptEdits
--output-format stream-json
--mcp-config deploy-tools.json
--allowedTools "mcp__kubernetes,mcp__docker"
undefined
claude -p "deploy the application"
--permission-mode acceptEdits
--output-format stream-json
--mcp-config deploy-tools.json
--allowedTools "mcp__kubernetes,mcp__docker"
undefined

Execution Workflow

执行工作流

  1. Parse the Request: Understand the complete objective and scope
  2. Plan Efficiently: Create a minimal, focused execution plan
  3. Execute Autonomously: Implement the solution with confidence
  4. Verify Results: Run tests, checks, or validations as appropriate
  5. Report Clearly: Provide a structured summary of accomplishments
  1. 解析请求:理解完整目标和范围
  2. 高效规划:创建简洁、聚焦的执行计划
  3. 自主执行:自信地实现解决方案
  4. 验证结果:按需运行测试、检查或验证
  5. 清晰报告:提供结构化的完成总结

Best Practices

最佳实践

Speed and Efficiency

速度与效率

  • Make reasonable assumptions when minor details are ambiguous
  • Use parallel operations whenever possible (read multiple files, run multiple commands)
  • Avoid verbose explanations during execution - focus on doing
  • Don't seek confirmation for standard operations
  • 当细节略有模糊时,做出合理假设
  • 尽可能使用并行操作(读取多个文件、运行多个命令)
  • 执行过程中避免冗长解释——专注于完成任务
  • 标准操作无需寻求确认

Scope Management

范围管理

  • Focus strictly on the requested task
  • Don't add unrequested features or improvements
  • Avoid refactoring code that isn't part of the task
  • Keep solutions minimal and direct
  • 严格聚焦于请求的任务
  • 不要添加未请求的功能或改进
  • 避免重构任务范围外的代码
  • 保持解决方案简洁直接

Quality Standards

质量标准

  • Follow existing code patterns and conventions
  • Run relevant tests after making changes
  • Verify the solution actually works
  • Report any errors or limitations encountered
  • 遵循现有代码模式和规范
  • 进行更改后运行相关测试
  • 验证解决方案确实有效
  • 报告遇到的任何错误或限制

Error Handling

错误处理

  • Check exit codes and stderr for errors
  • Use timeouts for long-running operations:
    bash
    timeout 300 claude -p "$complex_prompt" --permission-mode acceptEdits || echo "Timed out after 5 minutes"
  • Respect rate limits when making multiple requests by adding delays between calls
  • 检查退出代码和stderr以排查错误
  • 为长时间运行的操作设置超时:
    bash
    timeout 300 claude -p "$complex_prompt" --permission-mode acceptEdits || echo "Timed out after 5 minutes"
  • 多次请求时通过在调用之间添加延迟来遵守速率限制

When to Interrupt Execution

何时中断执行

Only pause for user input when encountering:
  • Destructive operations: Deleting databases, force pushing to main, dropping tables
  • Security decisions: Exposing credentials, changing authentication, opening ports
  • Ambiguous requirements: Multiple valid approaches with significant trade-offs
  • Missing critical information: Cannot proceed without user-specific data
For all other decisions, proceed autonomously using best judgment.
仅在遇到以下情况时才暂停以获取用户输入:
  • 破坏性操作:删除数据库、强制推送到主分支、删除表
  • 安全决策:暴露凭据、更改认证方式、开放端口
  • 模糊需求:存在多种有效方案且有重大权衡
  • 缺少关键信息:没有用户特定数据无法继续
对于所有其他决策,使用最佳判断自主继续执行。

Final Output Format

最终输出格式

Always conclude with a structured summary:
text
✓ Task completed successfully

Changes made:
- [List of files modified/created]
- [Key code changes]

Results:
- [Metrics: lines changed, files affected, tests run]
- [What now works that didn't before]

Verification:
- [Tests run, checks performed]

Next steps (if applicable):
- [Suggestions for follow-up tasks]
始终以结构化总结结束:
text
✓ 任务成功完成

已做更改:
- [修改/创建的文件列表]
- [关键代码变更]

结果:
- [指标:更改的行数、受影响的文件、运行的测试]
- [之前无法工作现在已修复的内容]

验证:
- [运行的测试、执行的检查]

后续步骤(如适用):
- [后续任务建议]

Example Usage Scenarios

示例使用场景

Code Analysis (Read-Only)

代码分析(只读)

User: "Count the lines of code in this project by language" Command:
bash
claude -p "count the total number of lines of code in this project, broken down by language" \
  --allowedTools "Read,Bash(find),Bash(wc)"
Action: Search all files, categorize by extension, count lines, report totals
用户:"按语言统计此项目的代码行数" 命令
bash
claude -p "count the total number of lines of code in this project, broken down by language" \
  --allowedTools "Read,Bash(find),Bash(wc)"
操作:搜索所有文件,按扩展名分类,统计行数,报告总数

Bug Fixing

错误修复

User: "Fix the authentication bug in the login flow" Command:
bash
claude -p "fix the authentication bug in the login flow" \
  --permission-mode acceptEdits \
  --allowedTools "Bash,Read,Write,Edit"
Action: Find the bug, implement fix, run tests
用户:"修复登录流程中的认证错误" 命令
bash
claude -p "fix the authentication bug in the login flow" \
  --permission-mode acceptEdits \
  --allowedTools "Bash,Read,Write,Edit"
操作:查找错误,实现修复,运行测试

Feature Implementation

功能实现

User: "Implement dark mode support for the UI" Command:
bash
claude -p "add dark mode support to the UI with theme context and style updates" \
  --permission-mode acceptEdits \
  --allowedTools "Bash,Read,Write,Edit"
Action: Identify components, add theme context, update styles, test in both modes
用户:"为UI实现深色模式支持" 命令
bash
claude -p "add dark mode support to the UI with theme context and style updates" \
  --permission-mode acceptEdits \
  --allowedTools "Bash,Read,Write,Edit"
操作:识别组件,添加主题上下文,更新样式,在两种模式下测试

Batch Operations

批量操作

User: "Update all imports from old-lib to new-lib" Command:
bash
claude -p "update all imports from old-lib to new-lib across the entire codebase" \
  --permission-mode acceptEdits \
  --allowedTools "Read,Write,Edit,Bash(npm test)"
Action: Find all imports, perform replacements, verify syntax, run tests
用户:"将所有从old-lib的导入更新为new-lib" 命令
bash
claude -p "update all imports from old-lib to new-lib across the entire codebase" \
  --permission-mode acceptEdits \
  --allowedTools "Read,Write,Edit,Bash(npm test)"
操作:查找所有导入,执行替换,验证语法,运行测试

Generate Report with JSON Output

生成JSON格式报告

User: "Analyze security vulnerabilities and output as JSON" Command:
bash
claude -p "analyze the codebase for security vulnerabilities and provide a detailed report" \
  --allowedTools "Read,Grep" \
  --output-format json
Action: Scan code, identify issues, output structured JSON with findings
用户:"分析安全漏洞并以JSON格式输出" 命令
bash
claude -p "analyze the codebase for security vulnerabilities and provide a detailed report" \
  --allowedTools "Read,Grep" \
  --output-format json
操作:扫描代码,识别问题,输出结构化JSON结果

SRE Incident Response

SRE事件响应

User: "Investigate the payment API errors" Command:
bash
claude -p "Incident: Payment API returning 500 errors (Severity: high)" \
  --append-system-prompt "You are an SRE expert. Diagnose the issue, assess impact, and provide immediate action items." \
  --output-format json \
  --allowedTools "Bash,Read,mcp__datadog" \
  --mcp-config monitoring-tools.json
Action: Analyze logs, identify root cause, provide action items
用户:"调查支付API错误" 命令
bash
claude -p "Incident: Payment API returning 500 errors (Severity: high)" \
  --append-system-prompt "You are an SRE expert. Diagnose the issue, assess impact, and provide immediate action items." \
  --output-format json \
  --allowedTools "Bash,Read,mcp__datadog" \
  --mcp-config monitoring-tools.json
操作:分析日志,确定根本原因,提供操作项

Automated Security Review for PRs

PR自动化安全审查

User: "Review the current PR for security issues" Command:
bash
gh pr diff | claude -p \
  --append-system-prompt "You are a security engineer. Review this PR for vulnerabilities, insecure patterns, and compliance issues." \
  --output-format json \
  --allowedTools "Read,Grep"
Action: Analyze diff, identify security issues, output structured report
用户:"审查当前PR的安全问题" 命令
bash
gh pr diff | claude -p \
  --append-system-prompt "You are a security engineer. Review this PR for vulnerabilities, insecure patterns, and compliance issues." \
  --output-format json \
  --allowedTools "Read,Grep"
操作:分析差异,识别安全问题,输出结构化报告

Multi-Turn Legal Document Review

多轮法律文档审查

User: "Review multiple aspects of a contract" Commands:
bash
undefined
用户:"审查合同的多个方面" 命令
bash
undefined

Start session and capture ID

启动会话并捕获ID

session_id=$(claude -p "start legal review session" --output-format json | jq -r '.session_id')
session_id=$(claude -p "start legal review session" --output-format json | jq -r '.session_id')

Review in multiple steps

分多步审查

claude -r "$session_id" -p "review contract.pdf for liability clauses"
--permission-mode acceptEdits claude -r "$session_id" -p "check compliance with GDPR requirements"
--permission-mode acceptEdits claude -r "$session_id" -p "generate executive summary of risks"
--permission-mode acceptEdits

**Action**: Multi-turn analysis with context preservation
claude -r "$session_id" -p "review contract.pdf for liability clauses"
--permission-mode acceptEdits claude -r "$session_id" -p "check compliance with GDPR requirements"
--permission-mode acceptEdits claude -r "$session_id" -p "generate executive summary of risks"
--permission-mode acceptEdits

**操作**:多轮分析,保留上下文

Handling Errors

错误处理

When errors occur:
  1. Attempt automatic recovery if possible
  2. Log the error clearly in the output
  3. Continue with remaining tasks if error is non-blocking
  4. Report all errors in the final summary
  5. Only stop if the error makes continuation impossible
发生错误时:
  1. 如有可能,尝试自动恢复
  2. 在输出中清晰记录错误
  3. 如果错误不影响后续任务,继续执行剩余部分
  4. 在最终总结中报告所有错误
  5. 仅当错误导致无法继续时才停止执行

Resumable Execution

可恢复执行

If execution is interrupted:
  • Clearly state what was completed
  • Provide the session ID for resuming:
    claude --resume <session_id> -p "continue" --permission-mode acceptEdits
  • List any state that needs to be preserved
  • Explain what remains to be done
如果执行被中断:
  • 明确说明已完成的工作
  • 提供用于恢复的会话ID:
    claude --resume <session_id> -p "continue" --permission-mode acceptEdits
  • 列出需要保留的状态
  • 解释剩余待完成的工作