claude-code-cli

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Claude Code CLI

Claude Code CLI

Installation

安装

bash
undefined
bash
undefined

Native (recommended)

原生方式(推荐)

NPM (deprecated)

NPM方式(已废弃)

npm install -g @anthropic-ai/claude-code

Verify: `claude --version`
npm install -g @anthropic-ai/claude-code

验证:`claude --version`

Authentication

认证

Environment Variables

环境变量

VariableDescriptionPriority
ANTHROPIC_API_KEY
API key from console.anthropic.comHigh (overrides OAuth)
CLAUDE_CODE_OAUTH_TOKEN
OAuth token for subscription authNormal
Warning: Setting
ANTHROPIC_API_KEY
bypasses subscription and uses pay-as-you-go API rates.
变量名描述优先级
ANTHROPIC_API_KEY
来自console.anthropic.com的API密钥高(覆盖OAuth)
CLAUDE_CODE_OAUTH_TOKEN
用于订阅认证的OAuth令牌普通
警告:设置
ANTHROPIC_API_KEY
会绕过订阅机制,采用按使用量付费的API费率。

For Headless/Sandbox Use

无头/沙箱环境使用

Since Claude Code requires browser-based OAuth, use one of:
  1. API Key (recommended for CI/sandboxes):
    bash
    export ANTHROPIC_API_KEY="sk-ant-..."
    claude -p "your prompt"
  2. OAuth Token Transfer (from authenticated machine):
    bash
    # On local machine: authenticate normally, then copy token
    # Location: ~/.config/claude-code/auth.json
    # Transfer to sandbox via environment variable
    export CLAUDE_CODE_OAUTH_TOKEN="token-from-auth-json"
由于Claude Code需要基于浏览器的OAuth认证,请使用以下方式之一:
  1. API密钥(CI/沙箱环境推荐):
    bash
    export ANTHROPIC_API_KEY="sk-ant-..."
    claude -p "your prompt"
  2. OAuth令牌迁移(从已认证的机器迁移):
    bash
    # 在本地机器:正常完成认证,然后复制令牌
    # 位置:~/.config/claude-code/auth.json
    # 通过环境变量迁移到沙箱
    export CLAUDE_CODE_OAUTH_TOKEN="token-from-auth-json"

Check Current Auth

检查当前认证状态

In interactive mode:
/status
在交互模式下输入:
/status

Non-Interactive Mode (-p / --print)

非交互模式(-p / --print)

For automated execution, use
-p
flag:
bash
claude -p "your prompt here"
This runs the prompt and exits (no REPL).
对于自动化执行,使用
-p
参数:
bash
claude -p "your prompt here"
该模式会运行提示指令后退出(不进入REPL)。

Essential Flags

核心参数

Core Flags

基础参数

FlagDescriptionExample
-p, --print
Non-interactive mode, exit after response
claude -p "explain this"
-c, --continue
Continue most recent conversation
claude -c -p "now fix it"
-r, --resume <id>
Resume specific session
claude -r "abc123" "continue"
--model <name>
Set model (
sonnet
,
opus
, or full name)
claude --model opus -p "..."
参数描述示例
-p, --print
非交互模式,返回结果后退出
claude -p "explain this"
-c, --continue
继续最近的对话
claude -c -p "now fix it"
-r, --resume <id>
恢复指定会话
claude -r "abc123" "continue"
--model <name>
设置模型(
sonnet
opus
或完整模型名)
claude --model opus -p "..."

Permission & Security

权限与安全

FlagDescription
--dangerously-skip-permissions
Skip ALL permission prompts (use with caution)
--allowedTools <tools>
Auto-approve specific tools without prompting
--disallowedTools <tools>
Block specific tools entirely
--permission-mode <mode>
Start in specific mode (e.g.,
plan
)
参数描述
--dangerously-skip-permissions
跳过所有权限提示(谨慎使用)
--allowedTools <tools>
自动批准指定工具,无需提示
--disallowedTools <tools>
完全禁用指定工具
--permission-mode <mode>
以指定模式启动(例如
plan

Tool Control

工具控制

bash
undefined
bash
undefined

Allow specific tools (comma-separated)

允许指定工具(逗号分隔)

claude -p "fix the bug" --allowedTools "Read,Edit,Bash"
claude -p "fix the bug" --allowedTools "Read,Edit,Bash"

Allow with prefix matching (e.g., any git command)

允许前缀匹配的工具(例如所有git命令)

claude -p "commit changes" --allowedTools "Bash(git:*)"
claude -p "commit changes" --allowedTools "Bash(git:*)"

Disable all tools

禁用所有工具

claude -p "explain this" --tools ""
claude -p "explain this" --tools ""

Use only specific tools

仅使用指定工具

claude -p "review code" --tools "Read,Grep,Glob"
undefined
claude -p "review code" --tools "Read,Grep,Glob"
undefined

Output Formats

输出格式

FlagValueDescription
--output-format
text
Plain text (default)
json
JSON with metadata
stream-json
Newline-delimited JSON streaming
bash
undefined
参数取值描述
--output-format
text
纯文本(默认)
json
带元数据的JSON格式
stream-json
按行分隔的JSON流
bash
undefined

Get JSON output

获取JSON格式输出

claude -p "summarize" --output-format json
claude -p "summarize" --output-format json

Parse with jq

使用jq解析

claude -p "summarize" --output-format json | jq -r '.result'
claude -p "summarize" --output-format json | jq -r '.result'

Structured output with schema

带Schema的结构化输出

claude -p "list functions" --output-format json
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}}}'
undefined
claude -p "list functions" --output-format json
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}}}'
undefined

System Prompt

系统提示词

FlagDescription
--system-prompt <text>
Replace entire system prompt
--append-system-prompt <text>
Add to default prompt (recommended)
--system-prompt-file <path>
Load replacement from file
--append-system-prompt-file <path>
Append from file
bash
undefined
参数描述
--system-prompt <text>
替换整个系统提示词
--append-system-prompt <text>
添加到默认提示词后(推荐)
--system-prompt-file <path>
从文件加载替换的系统提示词
--append-system-prompt-file <path>
从文件加载内容追加到默认提示词
bash
undefined

Append custom instructions (keeps defaults)

追加自定义指令(保留默认提示词)

claude -p "review this" --append-system-prompt "Focus on security vulnerabilities"
claude -p "review this" --append-system-prompt "Focus on security vulnerabilities"

Replace entire prompt

替换整个提示词

claude -p "task" --system-prompt "You are a Python expert"
undefined
claude -p "task" --system-prompt "You are a Python expert"
undefined

Budget & Limits

预算与限制

FlagDescription
--max-budget-usd <amount>
Maximum spend (print mode only)
--max-turns <n>
Limit agentic turns (print mode only)
bash
claude -p "refactor this file" --max-budget-usd 5.00 --max-turns 10
参数描述
--max-budget-usd <amount>
最大花费额度(仅适用于打印模式)
--max-turns <n>
限制智能体交互轮次(仅适用于打印模式)
bash
claude -p "refactor this file" --max-budget-usd 5.00 --max-turns 10

Session Management

会话管理

bash
undefined
bash
undefined

Get session ID from output

从输出中获取会话ID

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

Resume later

后续恢复会话

claude -p "continue" --resume "$session_id"
claude -p "continue" --resume "$session_id"

Continue most recent

继续最近的会话

claude -p "what was I doing?" --continue
undefined
claude -p "what was I doing?" --continue
undefined

Recommended Sandbox Configuration

推荐沙箱配置

For running in Daytona sandboxes:
bash
undefined
在Daytona沙箱中运行的配置:
bash
undefined

Full automated execution with tool access

带工具访问权限的完整自动化执行

ANTHROPIC_API_KEY="sk-ant-..." claude -p "Create a hello world Python script"
--dangerously-skip-permissions
--output-format json
--max-turns 20
ANTHROPIC_API_KEY="sk-ant-..." claude -p "Create a hello world Python script"
--dangerously-skip-permissions
--output-format json
--max-turns 20

Or with specific tool allowlist

或使用指定工具白名单

ANTHROPIC_API_KEY="sk-ant-..." claude -p "Fix the bug in auth.py"
--allowedTools "Read,Edit,Bash,Grep,Glob"
--output-format json
ANTHROPIC_API_KEY="sk-ant-..." claude -p "Fix the bug in auth.py"
--allowedTools "Read,Edit,Bash,Grep,Glob"
--output-format json

With OAuth token instead

或使用OAuth令牌

CLAUDE_CODE_OAUTH_TOKEN="token..." claude -p "Explain this codebase"
--dangerously-skip-permissions
undefined
CLAUDE_CODE_OAUTH_TOKEN="token..." claude -p "Explain this codebase"
--dangerously-skip-permissions
undefined

Exit Codes

退出码

CodeMeaning
0Success
1Error (check stderr)
代码含义
0成功
1错误(检查stderr)

Piped Input

管道输入

bash
undefined
bash
undefined

Pipe file content

管道传输文件内容

cat src/main.ts | claude -p "explain this code"
cat src/main.ts | claude -p "explain this code"

Pipe command output

管道传输命令输出

git diff | claude -p "review these changes"
git diff | claude -p "review these changes"

Pipe multiple files

管道传输多个文件

cat src/*.ts | claude -p "find security issues"
undefined
cat src/*.ts | claude -p "find security issues"
undefined

Common Patterns

常见使用场景

Code Review

代码审查

bash
git diff HEAD~1 | claude -p "Review these changes for bugs and improvements" \
  --append-system-prompt "Focus on security and performance" \
  --output-format json
bash
git diff HEAD~1 | claude -p "Review these changes for bugs and improvements" \
  --append-system-prompt "Focus on security and performance" \
  --output-format json

Bug Fix

修复Bug

bash
claude -p "Fix the failing test in tests/auth.test.ts" \
  --allowedTools "Read,Edit,Bash(npm test:*)" \
  --max-turns 15
bash
claude -p "Fix the failing test in tests/auth.test.ts" \
  --allowedTools "Read,Edit,Bash(npm test:*)" \
  --max-turns 15

Code Generation

代码生成

bash
claude -p "Create a REST API endpoint for user registration" \
  --dangerously-skip-permissions \
  --max-turns 30
bash
claude -p "Create a REST API endpoint for user registration" \
  --dangerously-skip-permissions \
  --max-turns 30

Explanation Only (No Tools)

仅代码解释(禁用工具)

bash
cat complex-file.ts | claude -p "Explain how this works" --tools ""
bash
cat complex-file.ts | claude -p "Explain how this works" --tools ""

Error Messages to Watch For

需要注意的错误信息

In sandbox output, watch for:
  • "Authentication failed"
    - Invalid token/key
  • "OAuth token has expired"
    - Need fresh token
  • "Invalid API key"
    - Check ANTHROPIC_API_KEY
  • "Rate limit exceeded"
    - Back off and retry
  • "Context length exceeded"
    - Reduce input size
在沙箱输出中,注意以下错误:
  • "Authentication failed"
    - 令牌/密钥无效
  • "OAuth token has expired"
    - 需要刷新令牌
  • "Invalid API key"
    - 检查
    ANTHROPIC_API_KEY
    是否正确
  • "Rate limit exceeded"
    - 请稍后重试
  • "Context length exceeded"
    - 减小输入内容大小

Notes

注意事项

  • Skills/slash commands (like
    /commit
    ) only work in interactive mode, not with
    -p
  • -p
    mode exits after completion; use
    --continue
    for multi-step tasks
  • --dangerously-skip-permissions
    gives full tool access - use in trusted environments only
  • Output buffering: Claude streams output, buffer at ~100ms for IPC efficiency
  • 技能/斜杠命令(如
    /commit
    )仅在交互模式下生效,
    -p
    模式下不支持
  • -p
    模式执行完成后会退出;如需多步骤任务,请使用
    --continue
    参数
  • --dangerously-skip-permissions
    会授予完全工具访问权限 - 仅在可信环境中使用
  • 输出缓冲:Claude会流式输出内容,为提高IPC效率,建议设置约100ms的缓冲时间