DEV Community

drake
drake

Posted on

claude code 使用文档(官方文档扩充版)

Claude Code 完整指南

> 本指南涵盖了截至 2025 年 7 月的所有可发现的 Claude Code 命令

> 包括许多在基础教程中未广泛知晓或未文档化的功能。

这是目前最完整的 Claude Code 命令参考。


如需更新和贡献,请访问 官方 Claude Code 文档

Claude Code
状态
许可证

访问:https://zebbern.github.io/ 获取更详细信息!

章节 状态
Windows、Linux、MacOS 安装指南
技巧和窍门
MCP 概览及使用方法
社区指南
故障排除
如何最优化使用 Claude Code

我通常用 Claude --dangerously-skip-permissions 启动 Claude,只有在你确切知道自己在做什么时才使用!


目录

  1. 快速开始
  2. 安装与设置
  3. 核心命令
  4. 会话命令
  5. 配置命令
  6. 标志参考
  7. 内置斜杠命令
  8. MCP 集成
  9. 配置
  10. 环境变量
  11. 安全与权限
  12. Claude CLI 配置
  13. Claude ~/.claude.json 配置指南
  14. 自动化与脚本
  15. 故障排除
  16. 高级功能
  17. 最佳实践

快速开始

# 快速安装

## 方法 1 – NPM(全局)⭐️ 官方
npm install -g @anthropic-ai/claude-code
# 需要 macOS / Linux / WSL 上的 Node 18+

## 方法 2 MacOS
brew install node
npm install -g @anthropic-ai/claude-code
# 遇到 claude bot 问题?运行 export PATH="$PATH:$(npm bin -g)"

## 方法 3 – Arch Linux AUR
yay -S claude-code        # 或 paru -S claude-code
# 与 npm 发布版本保持同步

## 方法 4 – Docker(容器化)
mkdir -p ~/.docker/cli-plugins
curl -SL https://github.com/docker/buildx/releases/download/v0.11.2/buildx-v0.11.2.linux-amd64 -o ~/.docker/cli-plugins/docker-buildx
chmod +x ~/.docker/cli-plugins/docker-buildx
curl -O https://raw.githubusercontent.com/RchGrav/claudebox/main/claudebox
chmod +x claudebox
# 当你不能触及主机系统时很有用

## 方法 5 – 通过 WSL 的 Windows(Anthropic 推荐路径)
# 1) 启用 WSL 2 并安装 Ubuntu
# 2) 在 Ubuntu 内:
sudo apt update && sudo apt install -y nodejs npm
npm install -g @anthropic-ai/claude-code
# 分步指南

# 你也可以在 vscode 或 cursor 中轻松打开整个项目的 claude code:
cursor .
# 或
code .
# cd 到你想要工作的目录并运行上述命令!
# 记住要安装 claude code 扩展

## 检查 claude 是否已安装
which claude
claude --version

# 交互模式
claude                      # 启动交互式 REPL
claude "your question"      # 以初始提示启动

# 单次模式
claude -p "analyze this"    # 快速查询并退出
cat file | claude -p "fix"  # 处理管道内容

# 管理
claude config              # 配置设置
claude update              # 更新到最新版本
claude mcp                 # 设置 MCP 服务器
Enter fullscreen mode Exit fullscreen mode

🚀 安装与设置

系统要求:

  • Node.js 16+ 或独立二进制文件
  • Anthropic API 密钥
  • 最少 4GB RAM(推荐 8GB+ 用于大型项目)
  • 用于 API 调用的互联网连接

支持的平台:

  • macOS(Intel/Apple Silicon)
  • Linux(Ubuntu 18+、Debian 10+、CentOS 7+)
  • Windows 10/11(推荐 WSL)[Win 10 未测试]

安装方法

方法 1:NPM 安装

# 全局安装
npm install -g @anthropic-ai/claude-code

# 验证安装
claude --version
Enter fullscreen mode Exit fullscreen mode

初始设置

1. API 密钥配置

# 必需:从 https://console.anthropic.com 获取你的 API 密钥
export ANTHROPIC_API_KEY="sk-your-key-here"

# 设为永久(选择你的 shell)
# Bash
echo 'export ANTHROPIC_API_KEY="sk-your-key-here"' >> ~/.bashrc
source ~/.bashrc

# Zsh
echo 'export ANTHROPIC_API_KEY="sk-your-key-here"' >> ~/.zshrc
source ~/.zshrc

# Fish
echo 'set -gx ANTHROPIC_API_KEY "sk-your-key-here"' >> ~/.config/fish/config.fish
Enter fullscreen mode Exit fullscreen mode

2. 基本配置

# 交互式设置
claude config

# 设置基本默认值
claude config set -g model claude-sonnet-4
claude config set -g verbose true
claude config set -g outputFormat text

# 测试安装
claude "Hello, Claude!"
claude /doctor  
Enter fullscreen mode Exit fullscreen mode

3. 我关闭的设置

export DISABLE_TELEMETRY=1
export DISABLE_ERROR_REPORTING=1
export DISABLE_NON_ESSENTIAL_MODEL_CALLS=1

# 安全默认值
claude config set allowedTools "Edit,View"
claude config set hasTrustDialogAccepted
claude config set hasCompletedProjectOnboarding 
claude config set ignorePatterns
claude config set --global
Enter fullscreen mode Exit fullscreen mode

健康检查与测试

# 基本功能测试
claude "Explain what you can do"

# 打印模式测试
claude -p "What is 2+2?"

# 工具权限测试
claude "Create a file called test.txt with 'Hello World'"
# 应该提示 Edit 权限

# 会话连续性测试
claude -c  # 应该从上一个会话继续
Enter fullscreen mode Exit fullscreen mode

健康检查

claude /doctor
预期输出可能包括:
# ✅ API Key: Valid
# ✅ Network: Connected  
# ✅ Model Access: Available
Enter fullscreen mode Exit fullscreen mode

核心命令

命令 描述 示例
claude 启动交互式 REPL claude
claude "<prompt>" 带初始提示的 REPL claude "help debug"
claude -p "<prompt>" 单次打印模式 claude -p "explain fn"
`cat file \ claude -p ""` 将 STDIN 管道传输到 Claude
claude update 自我更新到最新版本 claude update
claude mcp 启动 MCP 向导 claude mcp

会话命令

命令 描述 示例
claude -c / --continue 继续上一个会话 claude -c
claude -c -p "<prompt>" 继续 + 新提示(打印) claude -c -p "check types"
claude -r <id> 通过会话 ID 恢复 claude -r abc123
claude --resume <id> 长格式恢复 claude --resume abc123
claude --resume <name> 通过保存名称恢复 claude --resume sprint-review

配置命令

命令 描述 示例
claude config 交互式向导 claude config
claude config list 列出所有键 claude config list
claude config get <key> 获取值 claude config get theme
claude config set <key> <val> 设置值 claude config set theme dark
claude config add <key> <vals…> 追加到数组 claude config add env DEV=1
claude config remove <key> <vals…> 移除项目 claude config remove env DEV=1

标志参考

基本

标志 简写 描述 示例
--print -p 非交互模式 claude -p "help"
--continue -c 恢复上一个会话 claude --continue
--resume -r 通过 ID 恢复 claude --resume abc
--help -h 显示帮助 claude --help
--version -v 显示版本 claude --version

输出与流程(与 -p 一起使用)

标志 选项 示例
--output-format text, json, stream-json --output-format json
--input-format text, stream-json --input-format stream-json
--max-turns 整数 --max-turns 3
--system-prompt 字符串 --system-prompt "You are strict"
--append-system-prompt 字符串 --append-system-prompt "Add tests"

安全与权限

标志 描述 示例
--allowedTools <list> 工具白名单 --allowedTools "Read,View"
--disallowedTools <list> 工具黑名单 --disallowedTools "Bash"
--permission-mode <mode> 在权限模式下启动 --permission-mode plan
--permission-prompt-tool <tool> 用于权限检查的 MCP 工具 --permission-prompt-tool mcp__auth__prompt
--dangerously-skip-permissions 跳过所有提示(⚠️) --dangerously-skip-permissions

额外

标志 目的 示例
--add-dir <paths> 额外工作目录 --add-dir ../lib ../src
--model <name> 选择模型 --model claude-opus-4-20250514
--verbose 详细日志 --verbose
--mcp-config <file> 加载 MCP 服务器 --mcp-config servers.json

内置斜杠命令(交互式)

斜杠命令 目的
/help 列出斜杠命令
/add-dir 添加更多工作目录
/bug 向 Anthropic 报告错误
/clear 清除聊天历史
/compact 压缩对话
/config 配置菜单
/cost 令牌使用
/doctor 健康检查
/exit 退出 REPL
/init 生成 CLAUDE.md
/login / /logout 认证切换
/mcp 管理 MCP 服务器
/memory 编辑记忆
/model 更改模型
/permissions 工具权限
/pr_comments 查看 PR 评论
/review 请求代码审查
/sessions 列出会话
/status 系统/账户状态
/terminal-setup 安装 Shift+Enter 绑定
/vim 切换 vim 模式

根据 2025 年 7 月 4 日的 Anthropic 文档验证。


🔌 MCP 集成

理解 MCP(模型上下文协议)

什么是 MCP?
MCP 通过连接外部服务、数据库、API 和工具来扩展 Claude 的功能。

MCP 架构:

Claude Code ←→ MCP 协议 ←→ MCP 服务器 ←→ 外部服务
Enter fullscreen mode Exit fullscreen mode

MCP 设置与配置

基本 MCP 命令

claude mcp                    # 交互式 MCP 配置
claude mcp list              # 列出已配置的服务器            
claude mcp add <name> <cmd>  # 添加新服务器
claude mcp remove <name>     # 移除服务器
Enter fullscreen mode Exit fullscreen mode

MCP 配置文件

位置~/.claude.json

基于作用域的配置文件

用户/全局作用域:
全局 MCP 服务器
项目作用域:
项目作用域的服务器存储在项目根目录的 .mcp.json 文件中

{
  "mcpServers": {
    "git": {
      "command": "git-mcp-server",
      "args": [],
      "env": {}
    },
    "postgres": {
      "command": "postgres-mcp-server", 
      "args": ["--host", "localhost", "--port", "5432"],
      "env": {
        "POSTGRES_USER": "developer",
        "POSTGRES_PASSWORD": "dev_password",
        "POSTGRES_DB": "myapp_development"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

MCP 服务器

注意:下面的确切包名和安装命令可能不准确。请查阅官方 MCP 文档以获取当前的服务器包。

开发工具

# npm install -g git-mcp-server         

# claude mcp add git "git-mcp-server"
# claude mcp add github "github-mcp-server --token $GITHUB_TOKEN"
Enter fullscreen mode Exit fullscreen mode

数据库集成

npm install -g postgres-mcp-server               
npm install -g mysql-mcp-server                  
npm install -g sqlite-mcp-server               

# 设置示例
# export POSTGRES_URL="postgresql://user:password@localhost:5432/mydb"
# claude mcp add postgres "postgres-mcp-server --url $POSTGRES_URL"
Enter fullscreen mode Exit fullscreen mode

MCP 工具权限

# 允许特定的 MCP 工具
claude --allowedTools "mcp__git__commit,mcp__git__push"

# 允许来自特定服务器的所有工具
claude --allowedTools "mcp__postgres__*"

# 与内置工具结合
claude --allowedTools "Edit,View,mcp__git__*"
Enter fullscreen mode Exit fullscreen mode

⚙️ 配置

配置系统概述

Claude Code 使用分层配置系统:

  1. 命令行标志(最高优先级)
  2. 环境变量
  3. 项目配置(位置可能不同)
  4. 全局配置(可能是 ~/.claude.json
  5. 内置默认值(最低优先级)

配置文件

全局配置

位置~/.claude.json

{
  "model": "claude-sonnet-4",
  "verbose": true,
  "outputFormat": "text", 
  "allowedTools": ["Edit", "View"],
  "disallowedTools": [],
}
Enter fullscreen mode Exit fullscreen mode

项目配置

位置settings.json 或类似文件

{
  "model": "claude-sonnet-4",
  "systemPrompt": "You are a senior developer working on this project",
  "allowedTools": [
    "Edit",
    "View",
    "Bash(git:*)",
    "Bash(npm:*)"
  ],
}
Enter fullscreen mode Exit fullscreen mode

环境变量

核心变量

变量 必需 目的 示例
ANTHROPIC_API_KEY API 认证 sk-ant-api03-xxx
ANTHROPIC_MODEL 默认模型 claude-sonnet-4
ANTHROPIC_BASE_URL API 端点覆盖 https://api.anthropic.com

环境变量

环境变量 默认值 示例值 效果
DISABLE_NON_ESSENTIAL_MODEL_CALLS 0 1 跳过自动摘要、背景解释和 git diff 扫描 ⇒ 更快、更便宜。
MAX_THINKING_TOKENS ≈30‑40 k 50000 用于阅读代码、分析 diff 和规划的更高令牌预算。
DISABLE_TELEMETRY 0 1 阻止匿名使用和错误遥测。
CLAUDE_CODE_USE_BEDROCK 0 1 通过 AWS Bedrock 路由请求(需要 IAM 凭证;如果缺少则回退)。
CLAUDE_CODE_USE_VERTEX 0 1 通过 Google Vertex AI 路由请求(需要服务账户凭证;如果缺少则回退)。
环境变量 默认值 示例值 作用
HTTP_PROXY (未设置) http://proxy.company.com:8080 通过给定代理路由 HTTP 请求。
HTTPS_PROXY (未设置) https://proxy.company.com:8443 通过给定代理路由 HTTPS 请求。
NO_PROXY localhost,127.0.0.1 localhost,127.0.0.1,*.company.com 绕过代理的逗号分隔主机/IP。

如何设置

Shell(临时)

export HTTP_PROXY="http://proxy.company.com:8080"
export HTTPS_PROXY="https://proxy.company.com:8443"
export NO_PROXY="localhost,127.0.0.1,*.company.com"
claude "Test request via proxy"
Enter fullscreen mode Exit fullscreen mode

Shell 配置文件(持久)

# ~/.bashrc 或 ~/.zshenv
export HTTP_PROXY="http://proxy.company.com:8080"
export HTTPS_PROXY="https://proxy.company.com:8443"
export NO_PROXY="localhost,127.0.0.1,*.company.com"
Enter fullscreen mode Exit fullscreen mode

使用 source ~/.bashrc 重新加载。

GitHub Actions

env:
  HTTP_PROXY:  "http://proxy.company.com:8080"
  HTTPS_PROXY: "https://proxy.company.com:8443"
  NO_PROXY:    "localhost,127.0.0.1,*.company.com"
Enter fullscreen mode Exit fullscreen mode

安全与权限

权限系统

工作方式

  • Claude 在使用工具前会请求权限
  • 权限在每个会话中被记住
  • 危险操作需要确认

权限级别

级别 描述 风险 用例
交互式 为每个操作提示 开发工作
白名单 仅预批准的工具 中等 自动化脚本
危险 跳过所有权限 严重 仅限容器

工具权限模式

# 允许特定工具
claude --allowedTools "Edit,View"

# 允许工具类别
claude --allowedTools "Edit,View,Bash"

# 作用域权限(仅 Git 操作)
claude --allowedTools "Bash(git:*)"

# 多个作用域
claude --allowedTools "Bash(git:*),Bash(npm:*)"
Enter fullscreen mode Exit fullscreen mode

危险模式(严重安全功能)

# 危险 - 可能造成数据丢失
claude --dangerously-skip-permissions

# 仅在隔离环境中使用:
# ✅ 安全:隔离的 Docker 容器
# ❌ 绝不:生产系统、共享机器、有重要数据的系统
Enter fullscreen mode Exit fullscreen mode

安全最佳实践

1. 从严格限制开始

# 好:特定权限
claude --allowedTools "Edit,View,Bash(git:status)"

# 坏:广泛权限
claude --allowedTools "Bash"
Enter fullscreen mode Exit fullscreen mode

2. 保护敏感数据

# 好:环境变量
export DATABASE_URL="postgresql://user:pass@host/db"

# 坏:在命令中硬编码凭证
# claude "connect to postgresql://user:password123@host/db"
Enter fullscreen mode Exit fullscreen mode

3. 定期安全审计

# 检查当前权限
claude config get allowedTools
claude config get disallowedTools

# 查看配置
claude config list
Enter fullscreen mode Exit fullscreen mode

思考关键词

你的提示中的某些短语可以向 CLI 暗示你需要额外的推理时间。这些关键词不是官方公共 API 的一部分,所以请理解它们可能在未来版本中更改或消失。

层级 你可以使用的关键词 (不区分大小写)
层级 1 think
层级 2 think about it, think a lot, think deeply, think hard, think more, megathink
层级 3 think harder, think intensely, think longer, think really hard, think super hard, think very hard, ultrathink

快速示例

claude -p "We have a tricky concurrency bug. ultrathink and propose a fix."
Enter fullscreen mode Exit fullscreen mode
  • 关键词可以出现在提示的任何位置(大小写不重要)。
  • 如果存在多个关键词,最高层级优先。

⚠️ 注意: 因为这个机制没有文档记录,Anthropic 可能在没有通知的情况下更改或移除它。

Claude CLI 配置

配置键


先决条件

  1. 首先进行认证
   # 选项 1 – 环境变量(推荐用于脚本)
   export ANTHROPIC_API_KEY="sk-..."

   # 选项 2 – 在 Claude REPL 内交互式登录
   claude /login
Enter fullscreen mode Exit fullscreen mode
  1. 备份当前配置
   cp ~/.claude/claude.json ~/.claude/claude.json.bak

   # 这取决于你的 .json 安装位置,也可能在 ~/.claude/local/package.json
Enter fullscreen mode Exit fullscreen mode

如果 apiKeyHelper 配置错误或找不到 API 密钥,你会看到错误:

Error getting API key from apiKeyHelper (in settings or ~/.claude.json):
Enter fullscreen mode Exit fullscreen mode

在修改其他键之前修复认证。(docs.anthropic.com)


claude config 命令

命令模式 目的 示例
claude config list 显示所有当前设置 claude config list
claude config get <key> 显示单个设置 claude config get theme
claude config set -g <key> <value> 设置全局 claude config set -g theme dark
claude config add -g <key> <value> 追加到数组类型设置 claude config add -g env CLAUDE_CODE_ENABLE_TELEMETRY=1
claude config remove -g <key> <value> 从数组类型设置中移除 claude config remove -g env CLAUDE_CODE_ENABLE_TELEMETRY

(省略 -g 以针对当前项目而不是全局)


可编辑的键

典型值 安全示例 注释
apiKeyHelper 可执行脚本的路径 claude config set -g apiKeyHelper ~/.claude/key_helper.sh 脚本必须回显新的 API 密钥;必须可执行。 (docs.anthropic.com)
installMethod npm, brew, binary, deb, … claude config set -g installMethod npm 仅供参考。 (ainativedev.io)
autoUpdates true / false claude config set -g autoUpdates false 开启/关闭自动更新。 (docs.anthropic.com)
theme dark, light, light-daltonized, dark-daltonized claude config set -g theme dark CLI 颜色方案。 (docs.anthropic.com)
verbose true / false claude config set -g verbose true 显示完整的 Bash + 工具输出。 (docs.anthropic.com)
preferredNotifChannel iterm2, iterm2_with_bell, terminal_bell, notifications_disabled claude config set -g preferredNotifChannel terminal_bell 警报出现的位置。 (docs.anthropic.com)
shiftEnterKeyBindingInstalled true / false claude config set -g shiftEnterKeyBindingInstalled true 启用 Shift+Enter 换行。 (ainativedev.io)
editorMode vim, nano, emacs, default claude config set -g editorMode vim 用于长提示的编辑器。 (ainativedev.io)
hasUsedBackslashReturn true / false claude config set -g hasUsedBackslashReturn true 内部标志;很少更改。 (ainativedev.io)
supervisorMode true / false claude config set -g supervisorMode true 启用监督者功能。 (ainativedev.io)
autoCompactEnabled true / false claude config set -g autoCompactEnabled true 自动压缩聊天日志。 (ainativedev.io)
diffTool Diff 命令/路径 claude config set -g diffTool meld /diff 使用。 (ainativedev.io)
env KEY=value 或 JSON claude config set -g env CLAUDE_CODE_ENABLE_TELEMETRY=0 向每个会话注入环境变量。 (docs.anthropic.com)
tipsHistory [] 或 JSON 数组 claude config set -g tipsHistory [] 清除提示弹窗历史。 (ainativedev.io)
parallelTasksCount 整数 ≥ 1 claude config set -g parallelTasksCount 4 限制并发任务。 (ainativedev.io)
todoFeatureEnabled true / false claude config set -g todoFeatureEnabled true 启用实验性待办事项。 (ainativedev.io)
messageIdleNotifThresholdMs 整数(毫秒) claude config set -g messageIdleNotifThresholdMs 60000 警报前的空闲阈值。 (ainativedev.io)
autoConnectIde true / false claude config set -g autoConnectIde true 启动时自动连接到 IDE。 (ainativedev.io)

🔒 尝试设置任何其他键(例如 model)将抛出 Error: Cannot set '<key>'. Only these keys can be modified… – 通过 CLI 验证。


Claude ~/.claude.json 配置指南

全局配置文件位置

Claude Code 将全局设置存储在:

~/.claude.json
Enter fullscreen mode Exit fullscreen mode

基本配置结构

{
  "apiKeyHelper": "~/.claude/key_helper.sh",
  "installMethod": "npm",
  "autoUpdates": false,
  "theme": "dark",
  "verbose": true,
  "preferredNotifChannel": "terminal_bell",
  "shiftEnterKeyBindingInstalled": true,
  "editorMode": "vim",
  "supervisorMode": true,
  "autoCompactEnabled": true,
  "diffTool": "meld",
  "env": {
    "CLAUDE_CODE_ENABLE_TELEMETRY": "0",
    "DISABLE_NON_ESSENTIAL_MODEL_CALLS": "1"
  },
  "tipsHistory": [],
  "parallelTasksCount": 4,
  "todoFeatureEnabled": true,
  "messageIdleNotifThresholdMs": 60000,
  "autoConnectIde": true,
  "mcpServers": {
    "git": {
      "command": "git-mcp-server",
      "args": [],
      "env": {}
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

安全配置

{
  "allowedTools": ["Edit", "View", "Bash(git:*)"],
  "disallowedTools": ["Bash(rm:*)", "Bash(sudo:*)"],
  "permissionMode": "interactive",
  "dangerouslySkipPermissions": false
}
Enter fullscreen mode Exit fullscreen mode

自动化与脚本指南

GitHub Actions 集成

name: Claude Code Review
on:
  pull_request:
    branches: [main]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '18'
      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code
      - name: Run Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p "Review this PR for security issues" \
            --allowedTools "View" \
            --output-format json > review.json
      - name: Post Review
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = JSON.parse(fs.readFileSync('review.json', 'utf8'));
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: review.message
            });
Enter fullscreen mode Exit fullscreen mode

Git 钩子

#!/bin/bash
# .git/hooks/pre-commit

# 运行 Claude Code 进行预提交检查
claude -p "Review these changes for issues" \
  --allowedTools "View" \
  --max-turns 1 \
  --output-format text

if [ $? -ne 0 ]; then
  echo "Claude Code 检查失败"
  exit 1
fi
Enter fullscreen mode Exit fullscreen mode

脚本自动化

#!/bin/bash
# 自动化代码审查脚本

export ANTHROPIC_API_KEY="your-key-here"
export DISABLE_NON_ESSENTIAL_MODEL_CALLS=1

# 设置权限
ALLOWED_TOOLS="View,Edit,Bash(git:*)"

# 运行审查
claude -p "分析这个项目的代码质量并提供改进建议" \
  --allowedTools "$ALLOWED_TOOLS" \
  --output-format json \
  --max-turns 3 > review_results.json

# 处理结果
if [ $? -eq 0 ]; then
  echo "审查完成,结果保存在 review_results.json"
else
  echo "审查失败"
  exit 1
fi
Enter fullscreen mode Exit fullscreen mode

🔧 故障排除

常见问题

1. API 密钥问题

# 检查 API 密钥
claude /doctor

# 设置 API 密钥
export ANTHROPIC_API_KEY="sk-your-key-here"
claude /login
Enter fullscreen mode Exit fullscreen mode

2. 权限错误

# 检查当前权限
claude config get allowedTools

# 重置权限
claude config set allowedTools "Edit,View"
Enter fullscreen mode Exit fullscreen mode

3. 网络问题

# 检查网络连接
claude /doctor

# 设置代理
export HTTP_PROXY="http://proxy:8080"
export HTTPS_PROXY="https://proxy:8080"
Enter fullscreen mode Exit fullscreen mode

4. 安装问题

# 检查 Node.js 版本
node --version  # 需要 16+

# 重新安装
npm uninstall -g @anthropic-ai/claude-code
npm install -g @anthropic-ai/claude-code
Enter fullscreen mode Exit fullscreen mode

调试技巧

启用详细输出

claude --verbose -p "你的查询"
Enter fullscreen mode Exit fullscreen mode

检查配置

claude config list
Enter fullscreen mode Exit fullscreen mode

测试连接

claude "Hello, are you working?"
Enter fullscreen mode Exit fullscreen mode

🚀 高级功能

自定义 MCP 服务器

// custom-mcp-server.js
const { Server } = require('@anthropic-ai/mcp-server');

const server = new Server({
  name: 'custom-server',
  version: '1.0.0'
});

server.registerTool({
  name: 'custom-tool',
  description: '自定义工具',
  inputSchema: {
    type: 'object',
    properties: {
      query: { type: 'string' }
    }
  },
  handler: async (params) => {
    // 自定义逻辑
    return { result: `处理: ${params.query}` };
  }
});

server.start();
Enter fullscreen mode Exit fullscreen mode

环境特定配置

开发环境

{
  "model": "claude-sonnet-4",
  "allowedTools": ["Edit", "View", "Bash"],
  "verbose": true
}
Enter fullscreen mode Exit fullscreen mode

生产环境

{
  "model": "claude-sonnet-4",
  "allowedTools": ["View"],
  "verbose": false,
  "dangerouslySkipPermissions": false
}
Enter fullscreen mode Exit fullscreen mode

批量操作

# 批量处理文件
find . -name "*.js" -exec claude -p "优化这个文件" {} \;

# 批量审查
for file in src/*.js; do
  claude -p "审查 $file" --allowedTools "View" > "review_$file.txt"
done
Enter fullscreen mode Exit fullscreen mode

💡 最佳实践

1. 安全第一

# 始终从最小权限开始
claude --allowedTools "View"

# 逐步增加权限
claude --allowedTools "View,Edit"

# 避免危险模式(除非在容器中)
# claude --dangerously-skip-permissions  # 仅在安全环境中
Enter fullscreen mode Exit fullscreen mode

2. 高效使用

# 使用特定的提示
claude -p "找到并修复这个 React 组件中的性能问题"

# 而不是泛泛的
claude -p "帮我修复代码"
Enter fullscreen mode Exit fullscreen mode

3. 项目管理

# 在项目根目录创建 .mcp.json
{
  "mcpServers": {
    "project-db": {
      "command": "postgres-mcp-server",
      "args": ["--url", "$DATABASE_URL"]
    }
  }
}

# 使用项目特定的 CLAUDE.md
echo "# 项目上下文\n这是一个 React 应用..." > CLAUDE.md
Enter fullscreen mode Exit fullscreen mode

4. 持续集成

# .github/workflows/claude-review.yml
name: Claude Review
on: [pull_request]
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Review with Claude
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          npm install -g @anthropic-ai/claude-code
          claude -p "审查这个 PR 的代码质量和安全性" \
            --allowedTools "View" \
            --output-format json
Enter fullscreen mode Exit fullscreen mode

5. 性能优化

# 禁用非必要调用以提高速度
export DISABLE_NON_ESSENTIAL_MODEL_CALLS=1

# 增加思考令牌预算用于复杂任务
export MAX_THINKING_TOKENS=50000

# 禁用遥测
export DISABLE_TELEMETRY=1
Enter fullscreen mode Exit fullscreen mode

6. 团队协作

# 共享项目配置
# 团队成员可以克隆并使用相同的 .mcp.json

# 标准化工具权限
claude config set -g allowedTools "Edit,View,Bash(git:*,npm:*)"

# 使用一致的模型
claude config set -g model claude-sonnet-4
Enter fullscreen mode Exit fullscreen mode

总结

Claude Code 是一个强大的 AI 辅助开发工具,提供了丰富的功能和灵活的配置选项。通过理解和正确使用本指南中的命令和最佳实践,你可以:

  • 提高代码质量和开发效率
  • 自动化重复性任务
  • 集成到现有的开发工作流中
  • 安全地管理权限和访问控制
  • 扩展功能以满足特定需求

记住始终遵循安全最佳实践,从最小权限开始,并根据需要逐步增加访问权限。


本指南基于 2025 年 7 月的 Claude Code 版本 1.0.38 编写。

Top comments (0)