Claude Code CLI 超详细使用教程

本教程基于 2026 年 4 月的官方文档整理,覆盖从安装、登录、常用命令、斜杠命令、配置文件、权限模式、内存系统、子代理(Sub-agents)、技能(Skills)、钩子(Hooks)、MCP 服务、插件、IDE 集成、CI/CD 集成到性能优化与最佳实践的全部内容。

官方文档入口:https://code.claude.com/docs/en/overview


目录

  1. [Claude Code 是什么](#Claude Code 是什么)
  2. 系统要求与前置准备
  3. [安装 Claude Code](#安装 Claude Code)
  4. 登录与账号
  5. 核心概念:你必须先理解这些
  6. 快速上手:第一个会话
  7. [CLI 命令大全(命令行启动参数)](#CLI 命令大全(命令行启动参数))
  8. [CLI 启动旗标(Flags)大全](#CLI 启动旗标(Flags)大全)
  9. [斜杠命令大全(会话内 / 命令)](#斜杠命令大全(会话内 / 命令))
  10. [配置体系(settings.json 与目录优先级)](#配置体系(settings.json 与目录优先级))
  11. [CLAUDE.md 与内存系统](#CLAUDE.md 与内存系统)
  12. [权限模式(Permission Modes)](#权限模式(Permission Modes))
  13. [模型选择与思考强度(Effort Level)](#模型选择与思考强度(Effort Level))
  14. [Skills:让 Claude 拥有专业能力](#Skills:让 Claude 拥有专业能力)
  15. Sub-agents:分派子代理并行作战
  16. [Hooks:用确定性脚本武装 Claude](#Hooks:用确定性脚本武装 Claude)
  17. MCP:连接外部服务(GitHub、Slack、数据库等)
  18. 插件(Plugins)
  19. [Git 工作流:分支、Worktree、PR](#Git 工作流:分支、Worktree、PR)
  20. [Headless / 脚本化使用(-p 模式)](#Headless / 脚本化使用(-p 模式))
  21. [IDE 集成(VS Code 与 JetBrains)](#IDE 集成(VS Code 与 JetBrains))
  22. Web、桌面、Slack、移动端多形态
  23. [CI/CD 集成(GitHub Actions、GitLab CI)](#CI/CD 集成(GitHub Actions、GitLab CI))
  24. 成本控制与用量监控
  25. 最佳实践
  26. 常见问题与排查
  27. 完整示例:从零开始的真实工作流
  28. 参考链接汇总

1. Claude Code 是什么

Claude Code 是 Anthropic 出品的代理式(agentic)命令行工具。它不是一个聊天机器人,而是一个真正能在你终端里运行的开发助手:

  • 读取整个代码库,理解项目结构与依赖
  • 直接修改多个文件,不仅是给你贴一段代码
  • 执行 shell 命令(编译、测试、git 等)
  • 管理 Git 工作流(分支、提交、合并、PR)
  • 通过 MCP 协议连接外部服务(GitHub、Slack、数据库、Jira、Linear、Sentry 等)
  • 可分派子代理并行执行任务,并通过钩子(Hooks)注入确定性逻辑

它的核心定位是「给开发者用的、可扩展的代理基础设施」,而不是另一个 AI 聊天框。

截至 2026 年初,Anthropic 自身约 90% 的代码由 AI 生成,公共 GitHub 上每天有数十万次提交由 Claude Code 撰写。


2. 系统要求与前置准备

操作系统支持

平台 要求
macOS 13 (Ventura) 或更高
Linux Ubuntu 20.04+ / Debian 10+,或其他主流发行版
Windows Windows 10+,原生或 WSL(WSL 1/2 均可)

硬件 / 网络

  • 至少 4 GB 内存
  • 稳定的互联网连接(Claude 通过 API 调用模型)

Shell 兼容性

最佳支持 Bash / Zsh / Fish。Windows 下推荐 PowerShell 或 Git Bash。

特殊环境

  • Alpine Linux / 其他 musl 系统 :需额外安装 libgcc libstdc++ ripgrep,并设置 export USE_BUILTIN_RIPGREP=0
  • Windows 原生 :必须先安装 Git for Windows(WSL 不需要)

账号要求

需以下任一身份才能使用:

  • Claude 订阅(Pro / Max / Team / Enterprise)--- 最推荐
  • Anthropic Console 账号(按 API 量付费,需预付额度)
  • 企业云(Amazon Bedrock、Google Vertex AI、Microsoft Foundry)

3. 安装 Claude Code

⚠️ 注意:通过 npm 安装的方式已被官方废弃(虽然包仍然存在于 npm 上)。请使用下列推荐方式之一。

3.1 原生安装脚本(推荐)

macOS / Linux / WSL:

bash 复制代码
curl -fsSL https://claude.ai/install.sh | bash

Windows PowerShell:

powershell 复制代码
irm https://claude.ai/install.ps1 | iex

Windows CMD:

cmd 复制代码
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

原生安装的好处:自动后台更新,永远是最新版。

3.2 macOS Homebrew

bash 复制代码
# 稳定版(约比最新版滞后一周,会跳过有重大回归的版本)
brew install --cask claude-code

# 最新版(最新功能立即可用)
brew install --cask claude-code@latest

更新:

bash 复制代码
brew upgrade claude-code        # 或 claude-code@latest

3.3 Windows WinGet

powershell 复制代码
winget install Anthropic.ClaudeCode
winget upgrade Anthropic.ClaudeCode    # 升级

3.4 Linux 包管理器

Debian / Ubuntu / Fedora / RHEL / Alpine 也支持 apt / dnf / apk 安装,参见官方 setup 文档

3.5 验证安装

bash 复制代码
claude --version
# 或
claude -v

3.6 安装特定版本

bash 复制代码
claude install 2.1.118       # 安装具体版本
claude install stable        # 安装稳定版
claude install latest        # 安装最新版

3.7 升级与诊断

bash 复制代码
claude update                # 升级到最新
claude doctor                # 在终端外检查
# 或在会话内:
/doctor

4. 登录与账号

4.1 首次登录

bash 复制代码
claude
# 首次启动会自动弹出登录提示

或在已启动的会话内:

复制代码
/login

4.2 登录命令变体

bash 复制代码
claude auth login                    # 默认方式
claude auth login --email you@x.com  # 预填邮箱
claude auth login --sso              # 强制走 SSO
claude auth login --console          # 走 Anthropic Console(按 API 计费)

4.3 查看登录状态

bash 复制代码
claude auth status            # JSON 输出
claude auth status --text     # 人类可读
# 退出码:0 = 已登录,1 = 未登录

4.4 登出 / 切换账号

bash 复制代码
claude auth logout
# 或在会话内
/logout

切换账号在会话内用 /login 即可。

4.5 为 CI / 脚本生成长期 token

bash 复制代码
claude setup-token

会输出一个长期有效的 OAuth token(仅打印到终端,不会保存到磁盘),用于 CI 流水线、远程构建机等场景。需要订阅账号


5. 核心概念:你必须先理解这些

要真正用好 Claude Code,先掌握五个核心系统:

系统 作用
配置体系(Settings) 决定模型、主题、默认权限、钩子、MCP 等所有行为
权限系统(Permissions) 决定哪些工具/命令需要确认、哪些可自动执行、哪些禁止
钩子(Hooks) 在关键事件(工具调用前后、Prompt 提交时等)注入脚本,实现确定性自动化
MCP(Model Context Protocol) 让 Claude 调用外部服务(GitHub、Slack、数据库、Jira 等)
子代理(Sub-agents) 派生隔离的子 Claude 实例并行处理大型任务

加上 Skills(技能) 这一可复用知识包,构成 Claude Code 的全部扩展性。

三层使用模型

  • Core 层:你正在交互的主会话。负责编排和最终决策。
  • Extension 层CLAUDE.md、Skills、Hooks、MCP --- 配置你的工作流。
  • Delegation 层:Sub-agents 与 Worktree --- 把繁重或并行任务下放出去。

大多数新手只在 Core 层使用,导致上下文膨胀、成本飙升。资深用户会把探索和专项工作下放给 Delegation 层,Extension 层提前配置好,Core 层只做编排。


6. 快速上手:第一个会话

进入任意项目目录:

bash 复制代码
cd ~/projects/my-app
claude

第一步:让它理解项目

复制代码
what does this project do?

或更具体:

复制代码
what technologies does this project use?
where is the main entry point?
explain the folder structure

Claude 会按需读取文件 ,你不需要手动 @ 任何东西(虽然你也可以 @./src/auth.ts 显式引用)。

第二步:第一次改代码

复制代码
add a hello world function to the main file

Claude 会:

  1. 找到合适的文件
  2. 显示拟改动的 diff
  3. 等你确认(默认权限模式下)
  4. 写入

第三步:让它跑测试 / 用 Git

复制代码
run the test suite and fix any failures
what files have I changed?
commit my changes with a descriptive message
create a new branch called feature/login

第四步:解决一个 Bug

复制代码
There's a bug where users see a blank screen after entering wrong credentials.
Check src/auth/ and fix it. Add a regression test.

第五步:退出

复制代码
exit
# 或
/exit
# 或快捷键 Ctrl+D

7. CLI 命令大全(命令行启动参数)

这一节是「在终端里输入 claude xxx」时的命令。第 9 节才是会话内 /xxx

命令 说明 示例
claude 启动交互式会话 claude
claude "query" 带初始 prompt 启动 claude "explain this project"
claude -p "query" 单次查询后退出(SDK 模式) claude -p "explain this function"
`cat file claude -p "query"` 处理管道输入
claude -c 续接当前目录最近一次会话 claude -c
claude -c -p "query" 续接 + SDK 模式 claude -c -p "Check for type errors"
claude -r "<session>" "query" 按 ID 或名字恢复会话 claude -r "auth-refactor" "Finish this PR"
claude update 升级到最新版 claude update
claude install [version] 安装/重装原生二进制 claude install stable
claude auth login 登录 claude auth login --console
claude auth logout 登出 claude auth logout
claude auth status 显示登录状态(JSON) claude auth status --text
claude agents 列出所有已配置的子代理 claude agents
claude auto-mode defaults 输出内置 auto 模式分类规则(JSON) claude auto-mode defaults > rules.json
claude mcp 配置 MCP 服务 见 MCP 章节
claude plugin 管理插件,别名 claude plugins claude plugin install code-review@claude-plugins-official
claude remote-control 启动远程控制服务(从 claude.ai 控制本地终端) claude remote-control --name "My Project"
claude setup-token 生成 CI 用长期 token claude setup-token

拼错命令时,Claude Code 会给出最近匹配建议,例如 claude udpateDid you mean claude update?


8. CLI 启动旗标(Flags)大全

⚠️ claude --help 不会列出所有 flag,flag 不在 --help 里不代表它不存在。下面是完整列表(按用途分类)。

8.1 模型与思考强度

Flag 说明 示例
--model 指定模型,可用别名(sonnetopus)或全名 claude --model claude-sonnet-4-6
--effort 思考强度:low / medium / high / xhigh / max(仅当前会话) claude --effort high
--fallback-model 主模型过载时自动降级(仅 print 模式) claude -p --fallback-model sonnet "..."

8.2 会话与目录

Flag 说明
--add-dir 增加可读写的工作目录(多个用空格分隔)
--continue, -c 续接当前目录最近会话
--resume, -r 按 ID/名字恢复会话,无参数则弹出选择器
--session-id 用指定 UUID 创建会话
--name, -n 给会话设置显示名(出现在 /resume 和终端标题)
--fork-session 恢复会话时创建新 session ID(与 --resume/--continue 联用)
--from-pr 恢复绑定到指定 PR 的会话(接受 PR 号或 GitHub/GitLab/Bitbucket URL)
--worktree, -w 在隔离的 git worktree 内启动 Claude,路径为 <repo>/.claude/worktrees/<n>
--tmux 为 worktree 创建 tmux 会话(需配合 --worktree),iTerm2 下用原生面板,可加 --tmux=classic

8.3 权限与工具

Flag 说明
--permission-mode 启动时进入指定权限模式:default/acceptEdits/plan/auto/dontAsk/bypassPermissions
--allowedTools 无需确认即可执行的工具,支持模式匹配
--disallowedTools 完全禁止的工具
--tools 限定可用工具,""=全禁,"default"=全开
--allow-dangerously-skip-permissions bypassPermissions 加入 Shift+Tab 切换循环(但不立即进入)
--dangerously-skip-permissions 等价于 --permission-mode bypassPermissions
--permission-prompt-tool 在非交互模式下指定 MCP 工具来处理权限询问

8.4 系统提示词

Flag 行为
--system-prompt 替换整个默认系统提示词
--system-prompt-file 用文件内容替换
--append-system-prompt 追加文本到默认提示词后
--append-system-prompt-file 用文件内容追加

绝大多数情况下用 append 系列。replace 系列只在你想完全控制系统提示时使用,会失去 Claude Code 的内置能力。

8.5 输入输出(Headless)

Flag 说明
--print, -p 打印响应后退出(脚本/SDK 模式)
--input-format text / stream-json
--output-format text / json / stream-json
--include-partial-messages 输出包含流式增量事件(需 --print--output-format stream-json
--include-hook-events 输出包含所有钩子事件(需 --output-format stream-json
--replay-user-messages stdin 进来的用户消息回显到 stdout
--max-turns 限制代理回合数(仅 print 模式)
--max-budget-usd 美元预算上限(仅 print 模式)
--no-session-persistence 不保存会话(仅 print 模式)
--json-schema 让最终输出符合给定 JSON Schema

8.6 配置与扩展

Flag 说明
--settings 加载额外的 settings JSON 文件或字符串
--setting-sources 指定加载哪些来源:user,project,local
--mcp-config 从 JSON 文件/字符串加载 MCP 配置
--strict-mcp-config 仅使用 --mcp-config 提供的 MCP,忽略其他
--plugin-dir 仅本次会话加载某目录的插件(可重复)
--agent 指定本会话使用的代理
--agents 用 JSON 动态定义子代理
--bare 极简模式:跳过 hooks/skills/plugins/MCP/CLAUDE.md 自动发现,仅保留 Bash/读/写文件,启动最快,常用于脚本
--betas 添加 beta 头(仅 API key 用户)

8.7 其他

Flag 说明
--ide 启动时自动连 IDE(如有唯一可用 IDE)
--init 运行 init 钩子并进入交互模式
--init-only 只跑 init 钩子,不进入交互
--maintenance 运行 maintenance 钩子并进入交互
--chrome / --no-chrome 启用/禁用 Chrome 浏览器集成(用于 Web 自动化与测试)
--remote claude.ai 上创建一个新 Web 会话
--remote-control, --rc 启动可被 claude.ai 远程控制的本地会话
--teleport 把 Web 会话拉回本地终端
--teammate-mode 队友 agent 显示方式:auto / in-process / tmux
--debug 调试模式,可加分类过滤 "api,hooks""!statsig"
--debug-file <path> 调试日志写入文件
--verbose 显示完整逐回合输出
--exclude-dynamic-system-prompt-sections 把机器相关段(cwd、env、git status 等)从系统提示移到首条用户消息,提升多用户场景的提示缓存复用
--disable-slash-commands 本会话禁用所有斜杠命令与 skills
--version, -v 输出版本号

9. 斜杠命令大全(会话内 / 命令)

在会话内输入 / 会列出所有可用命令;输入 / + 字母可过滤。

9.1 会话与上下文

命令 作用
/clear(别名 /reset/new 清空对话历史,释放上下文
/compact [指令] 压缩对话,可指定保留重点
/context 用彩色网格可视化当前上下文使用情况,并给出优化建议
/branch [name](别名 /fork 在当前点为对话开分支,原会话保留可用 /resume 回去
/resume [session](别名 /continue 按 ID/名字恢复对话,或弹出选择器
/rename [name] 重命名当前会话,名字会显示在提示栏上
/rewind(别名 /checkpoint 倒回到对话/代码的某个点(参见 checkpointing
/copy [N] 复制最近的助手回复,/copy 2 复制倒数第二条;有代码块时弹出选择器,按 w 写入文件(SSH 场景特别有用)
/export [filename] 导出对话为纯文本
/diff 交互式 diff 查看器,可在「整体 git diff」和「每回合 diff」间切换
/exit(别名 /quit 退出

9.2 配置与外观

命令 作用
/config(别名 /settings 打开设置界面
/theme 切换主题(含色盲友好与 ANSI 主题)
`/color [color default]`
/statusline 配置状态栏,可让 Claude 自动从你的 shell prompt 推断
/keybindings 打开/创建快捷键配置文件
/terminal-setup 在 VS Code/Alacritty/Warp 等终端配置 Shift+Enter 等快捷键

9.3 模型与权限

命令 作用
/model [model] 切换模型,立即生效。支持的模型可用左右键调思考强度
`/effort [low medium
/permissions(别名 /allowed-tools 管理 allow/ask/deny 规则,查看 auto 模式拒绝记录
/plan [描述] 进入 plan 模式,可附带任务直接开始
`/fast [on off]`
/sandbox 切换 sandbox 模式(仅支持的平台可用)

9.4 项目初始化

命令 作用
/init 在项目里生成 CLAUDE.md 指南。CLAUDE_CODE_NEW_INIT=1 启用交互式向导(含 skills、hooks、个人记忆)
/memory 编辑 CLAUDE.md,启停 auto-memory,查看自动条目
/add-dir <path> 给当前会话加一个工作目录

9.5 工具与扩展

命令 作用
/agents 管理子代理
/skills 列出可用 skills
/hooks 查看 hook 配置
/mcp 管理 MCP 服务连接与 OAuth
/plugin 管理插件
/reload-plugins 重载插件无需重启

9.6 内置 Skill 命令(用 / 触发的预制工作流)

命令 作用
/batch <指令> 大杀器 。把大型变更拆为 5--30 个独立单元,每个起一个隔离 worktree 的子 agent 并行做,最后开 PR。例:/batch migrate src/ from Solid to React
/loop [interval] [prompt](别名 /proactive 周期性执行 prompt。省略 interval 则 Claude 自配速。例:/loop 5m check if the deploy finished
/simplify [focus] 同时派 3 个评审子 agent 检查最近改动的代码,聚合发现并修复。例:/simplify focus on memory efficiency
/debug [描述] 启用调试日志并分析
/claude-api 加载 Claude API 参考资料(识别 Python/TS/Java/Go/Ruby/C#/PHP/cURL)。导入 anthropic/@anthropic-ai/sdk 时也会自动激活

9.7 Git / PR / 安全

命令 作用
/security-review 分析当前分支待提交的改动,找注入、鉴权、数据暴露等问题
/autofix-pr [prompt] 让 Claude Code on the Web 监视当前分支的 PR,CI 失败或评审留言时自动修复并推送(需 gh CLI)
/install-github-app 配置 Claude GitHub Actions 应用

9.8 用量与诊断

命令 作用
/cost 显示 token 用量统计
/usage 计划用量与速率限制状态
/stats 每日用量、会话历史、连续天数、模型偏好
/insights 分析会话报告,找出常用领域、交互模式、卡点
/status 设置界面的 Status 面板(版本、模型、账号、连通性)
/doctor 诊断安装与设置,按 f 让 Claude 修复
/release-notes 交互式 changelog 浏览
/feedback(别名 /bug 提交反馈

9.9 其他

命令 作用
/btw <问题> 在不污染主对话的情况下问个题外话
/help 显示帮助
/login / /logout 登录登出
/upgrade 升级套餐
/extra-usage 配置额度耗尽后的备用用量
/voice 切换语音听写(需 Claude.ai 账号)
/teleport(别名 /tp 把 Web 会话拉回当前终端(含分支与对话)
/desktop(别名 /app 在桌面 App 续接当前会话(仅 macOS/Windows)
/mobile(别名 /ios/android 显示移动 App 下载二维码
/passes 分发免费一周 Claude Code 给朋友(账号合格才显示)
/team-onboarding 基于近 30 天的会话/命令/MCP 使用历史生成团队 onboarding 指南
/web-setup 用本地 gh 凭据把 GitHub 连接到 Claude Code on the Web
/install-slack-app 安装 Slack 应用,OAuth 流程自动开浏览器
/setup-bedrock / /setup-vertex 引导式配置 Bedrock/Vertex

MCP 命令 :连上 MCP 服务后,服务器自身暴露的 prompt 会以 /mcp__<server>__<prompt> 形式出现在斜杠命令里。


10. 配置体系(settings.json 与目录优先级)

Claude Code 支持三层配置,优先级由高到低:

  1. local<project>/.claude/settings.local.json(仅本机本项目,git 忽略)
  2. project<project>/.claude/settings.json(项目共享,提交到 git)
  3. user~/.claude/settings.json(你的全局默认)

启动时可用 --setting-sources user,project,local 或环境变量限定加载哪些层。

10.1 settings.json 常见字段

jsonc 复制代码
{
  // 默认模型
  "model": "claude-sonnet-4-6",

  // 启动权限模式
  "defaultMode": "default",   // default | acceptEdits | plan | auto | dontAsk | bypassPermissions

  // 权限规则
  "permissions": {
    "allow": [
      "Bash(git diff:*)",
      "Bash(git log:*)",
      "Bash(npm test:*)",
      "Read",
      "Edit"
    ],
    "ask": [
      "Bash(git push:*)"
    ],
    "deny": [
      "Bash(rm -rf:*)",
      "Bash(curl:*)",
      "Edit(.env*)"
    ]
  },

  // 钩子
  "hooks": {
    "PostToolUse": [
      {
        "matcher": { "tool": "Edit" },
        "command": "npx prettier --write $CLAUDE_HOOK_FILE"
      }
    ]
  },

  // MCP 服务
  "mcpServers": {
    "github": {
      "type": "url",
      "url": "https://api.githubcopilot.com/mcp/",
      "headers": { "Authorization": "Bearer ${GITHUB_TOKEN}" }
    }
  },

  // 思考强度
  "effort": "medium",

  // 主题
  "theme": "dark",

  // 状态栏自定义
  "statusLine": "git_branch model cost"
}

10.2 通过命令查看与编辑

  • /config --- 图形化设置界面
  • claude --settings ./custom.json --- 临时加载额外设置
  • claude --setting-sources user,project --- 只加载部分层

10.3 .claude/ 目录结构

一个完整项目的 .claude/ 目录通常长这样:

复制代码
.claude/
├── settings.json              # 项目共享设置
├── settings.local.json        # 本机覆盖(git 忽略)
├── CLAUDE.md                  # 项目内存(非必需,根目录也行)
├── agents/                    # 项目子代理
│   ├── reviewer.md
│   └── tester.md
├── skills/                    # 项目 skills
│   └── payments/SKILL.md
├── hooks/                     # 钩子脚本
│   └── format-on-save.sh
├── commands/                  # 自定义斜杠命令
│   └── ship.md
└── worktrees/                 # 由 --worktree 自动创建
    └── feature-auth/

11. CLAUDE.md 与内存系统

CLAUDE.md 是 Claude 启动时自动加载的上下文文件,用来教它你的项目背景、约定和偏好。

11.1 三层内存

层级 路径 用途
项目内存 <project>/CLAUDE.md<project>/.claude/CLAUDE.md 团队共享:架构、约定、命令
本地内存 <project>/CLAUDE.local.md 本机覆盖(git 忽略)
用户内存 ~/.claude/CLAUDE.md 你跨项目的偏好

11.2 一份示例 CLAUDE.md

markdown 复制代码
# Project: Acme Web App

## Tech Stack
- Next.js 14, React 18, TypeScript strict
- PostgreSQL via Prisma
- Tailwind CSS, shadcn/ui

## Conventions
- Use functional components, hooks-only
- All API routes under `app/api/*` must validate input with Zod
- Never log PII (emails, names) --- use the redacted logger in `src/lib/log.ts`

## Useful Commands
- `pnpm dev` --- start dev server on port 3000
- `pnpm test` --- run vitest
- `pnpm db:migrate` --- apply Prisma migrations
- `pnpm typecheck` --- strict TS check

## Architecture Notes
- Auth handled by NextAuth in `src/lib/auth.ts`
- Background jobs use BullMQ, see `src/jobs/`

## Don't
- Don't add new dependencies without asking
- Don't edit anything in `prisma/migrations/` directly

11.3 初始化与维护

  • /init --- 让 Claude 扫描项目并自动写一份初版
  • CLAUDE_CODE_NEW_INIT=1 --- 启用交互式向导
  • /memory --- 编辑、查看、启停 auto-memory

11.4 Auto-memory(自动记忆)

启用后,Claude 会从对话中自动提取 值得记住的事实写入 CLAUDE.md,比如「用户更喜欢 pnpm 而不是 npm」。可在 /memory 里查看条目并取舍。

11.5 引用其他文件

CLAUDE.md 里写:

markdown 复制代码
See @./docs/ARCHITECTURE.md for the full picture.
See @./BUSINESS_RULES.md for domain rules.

Claude 会在需要时按需读取。


12. 权限模式(Permission Modes)

权限系统决定哪些工具可自动执行、哪些需要你确认、哪些被禁用

12.1 内置工具与默认权限

工具 默认
ReadGlobGrepWebSearchLSP 自动允许(只读)
EditWriteBashWebFetch 需要确认

LSP(v2.0.74+)支持跳转定义、查找引用、悬浮文档,需要项目里装好语言服务器。

12.2 模式列表

模式 行为
default 标准模式,破坏性操作前问
acceptEdits 自动接受文件编辑,但 Bash 仍要问
plan 只规划不执行,让 Claude 提出方案再让你审
auto 由内置分类器决定哪些自动批,规则可 claude auto-mode defaults 查看
dontAsk 用允许/拒绝规则,不问
bypassPermissions 危险:跳过所有权限检查

12.3 切换方式

  • 启动时:claude --permission-mode plan
  • 会话内:按 Shift+Tab 在已启用的模式间循环
  • /permissions 查看与编辑规则
  • /plan 直接进入 plan 模式

12.4 规则语法

jsonc 复制代码
"permissions": {
  "allow": [
    "Bash(git status)",          // 完全匹配
    "Bash(git log:*)",            // 通配符
    "Bash(npm test:*)",
    "Edit(src/**/*.ts)",          // glob
    "Read"                        // 整个工具
  ],
  "ask":   ["Bash(git push:*)"],
  "deny":  ["Bash(rm -rf:*)", "Edit(.env*)", "Bash(curl:*)"]
}

deny > ask > allow。匹配优先级最高的规则胜出。

12.5 安全建议

  • 生产代码库 :把 bypassPermissions 加入 deny 列表
  • 机密文件.env、密钥、证书一律 deny
  • 危险命令rm -rfcurl | shsudo 一律 deny
  • 审计 :定期 /permissions → 「Review auto-mode denials」

13. 模型选择与思考强度(Effort Level)

13.1 三档模型

模型 适合 上下文
Opus 4.6 复杂多步规划、棘手 bug、架构设计 200K
Sonnet 4.6 日常开发主力(Pro/Max5 推荐默认) 200K
Haiku 4.5 简单编辑、样板代码、并行子代理 200K

切换:

复制代码
/model
/model claude-opus-4-6
/model sonnet

或启动时:claude --model claude-haiku-4-5,或环境变量:export ANTHROPIC_MODEL=claude-sonnet-4-6

13.2 思考强度

/effort 控制 extended thinking 的预算:

  • low / medium / high --- 持久化
  • max --- 当前会话,需 Opus 4.6
  • auto --- 模型默认

你按思考 token 计费。在 prompt 里写「think harder」并不会 多分配预算,要用 /effort 切。

简单任务(重命名、补类型注解、文档微调)开 low;多文件重构、复杂调试开 high/max


14. Skills:让 Claude 拥有专业能力

Skills 是 Markdown 格式的专业能力包,告诉 Claude 在某些场景下「该怎么干」。它们用自然语言触发,由 Claude 自己决定何时调用。

14.1 一个最小 Skill

.claude/skills/payments/SKILL.md

markdown 复制代码
---
name: payments
description: |
  Use this skill when working with payment, refund, transaction, charge,
  or invoice code. Activates on edits to src/payments/** and any mention
  of Stripe webhooks, refund logic, or chargeback handling.
---

# Payments Domain Expertise

## Business Rules
- All refunds must check the 30-day window
- Partial refunds require the original charge ID
- Never expose `stripe_secret` in logs

## Patterns We Use
- Webhook handlers live in `src/payments/webhooks/`
- All amounts are stored as integer cents
- Use `idempotency_key` on every Stripe API call

See @./BUSINESS_RULES.md for detailed business logic.
See @./COMPLIANCE.md for regulatory requirements.

写好后,碰到付款相关任务 Claude 会自动按这份 skill 工作 --- 你不需要 /skill 调用

14.2 触发的关键

description 决定 Claude 是否激活该 skill。先写好 description

  1. 它提供什么
  2. 具体在何种条件下触发
  3. 例子越具体越好

14.3 Bundled Skills(内置)

/batch/loop/simplify/debug/claude-api 都是内置 skill,本质是同一机制。

14.4 官方公共 skills

Anthropic 维护了一组官方 skills:docxpptxxlsxpdfpdf-readingfile-readingfrontend-design 等。详见仓库:https://github.com/anthropics/claude-code


15. Sub-agents:分派子代理并行作战

子代理(sub-agent)= 派生一个独立上下文窗口 的 Claude 实例去做子任务,与主会话并行,完成后只把结果回传主会话,不污染主上下文。

15.1 什么时候用

  • 一次性改大量文件(每个 agent 一批)
  • 并行独立审计(安全/性能/测试覆盖率各派一个)
  • 大规模内容生成
  • 多步独立流水线

15.2 定义子代理

.claude/agents/reviewer.md

markdown 复制代码
---
name: reviewer
description: Performs thorough code review focused on security and performance.
tools: [Read, Grep, Glob]
model: opus
---

You are a senior code reviewer.
- Focus on injection risks, auth bugs, race conditions
- Check for N+1 queries and unbounded loops
- Output findings as a numbered list with file:line references

tools 限定该子代理可用工具,model 可不同于主会话。

15.3 调用

主会话直接说人话:

复制代码
Use the reviewer agent on src/auth/ and the changes in this branch.
Then use the tester agent to write missing tests for any uncovered paths.

或显式:claude --agent reviewer "review src/auth/"

15.4 动态定义

bash 复制代码
claude --agents '{
  "reviewer": {
    "description": "Reviews code",
    "prompt": "You are a code reviewer focused on security."
  }
}'

15.5 列出与管理

bash 复制代码
claude agents          # CLI
/agents                # 会话内

15.6 并行 worktree

/batch自动给每个子代理开独立 git worktree,互不干扰。也可手动:

bash 复制代码
claude -w feature-auth          # 在 .claude/worktrees/feature-auth 启动
claude -w feature-auth --tmux   # 还开 tmux 面板

16. Hooks:用确定性脚本武装 Claude

Hooks 是在 Claude 生命周期的特定事件自动执行的 shell 命令 。它们是确定性的(固定运行),不像 prompt 那样靠模型判断。

16.1 事件类型(部分)

事件 触发时机
PreToolUse 工具调用前
PostToolUse 工具调用后
UserPromptSubmit 你按下回车提交 prompt
SessionStart 会话开始
Notification 需要通知用户时
Stop 助手回合结束
SubagentStop 子代理结束

16.2 例子:每次编辑后自动格式化

.claude/settings.json

jsonc 复制代码
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": { "tool": "Edit", "filePattern": "*.ts" },
        "command": "npx prettier --write \"$CLAUDE_HOOK_FILE\""
      },
      {
        "matcher": { "tool": "Edit", "filePattern": "*.py" },
        "command": "ruff format \"$CLAUDE_HOOK_FILE\""
      }
    ],
    "PreToolUse": [
      {
        "matcher": { "tool": "Bash", "commandPattern": "git push*" },
        "command": ".claude/hooks/check-secrets.sh"
      }
    ]
  }
}

16.3 钩子可拒绝操作

钩子脚本退出码 0 = 通过;非 0 = 拒绝该工具调用,stderr 会作为错误反馈给 Claude。

bash 复制代码
# .claude/hooks/check-secrets.sh
#!/usr/bin/env bash
if git diff --cached | grep -E "(api_key|secret_key|password)\s*=\s*['\"]" >/dev/null; then
  echo "Detected hardcoded secret in staged changes. Aborting." >&2
  exit 1
fi

16.4 查看与调试

  • /hooks --- 查看当前钩子配置
  • claude --debug "hooks" --- 查看钩子触发日志
  • claude -p --output-format stream-json --include-hook-events ... --- 程序消费

17. MCP:连接外部服务(GitHub、Slack、数据库等)

MCP(Model Context Protocol) 是开放标准,让 Claude 通过统一协议调用任意外部服务。社区已有 300+ 服务可接。

17.1 添加一个 MCP 服务

最常见用 CLI 添加:

bash 复制代码
# 添加一个 stdio 模式的 MCP(本地脚本)
claude mcp add github npx @modelcontextprotocol/server-github

# 添加一个 url 模式的 MCP(远程 SSE)
claude mcp add asana --url https://mcp.asana.com/sse

或写进 settings.json

jsonc 复制代码
{
  "mcpServers": {
    "github": {
      "type": "stdio",
      "command": "npx",
      "args": ["@modelcontextprotocol/server-github"],
      "env": { "GITHUB_TOKEN": "${GITHUB_TOKEN}" }
    },
    "postgres": {
      "type": "stdio",
      "command": "npx",
      "args": ["@modelcontextprotocol/server-postgres", "postgresql://..."]
    },
    "linear": {
      "type": "url",
      "url": "https://mcp.linear.app/sse"
    }
  }
}

17.2 管理与认证

  • /mcp --- 列出连接、触发 OAuth
  • claude mcp list / claude mcp remove <name>
  • --mcp-config ./mcp.json --- 临时加载
  • --strict-mcp-config --- 仅用临时配置,忽略其他

17.3 用 MCP 服务

直接说人话:

复制代码
Find Linear issues assigned to me with priority high
Open a GitHub PR from this branch with the title "fix: resolve login race condition"
Query the orders table for users who churned last month

17.4 MCP 暴露的 prompt

服务器可暴露预制 prompt,会自动出现在斜杠命令中:

复制代码
/mcp__github__create-pr
/mcp__linear__triage-bugs

18. 插件(Plugins)

插件是打包好的能力组合:可以同时包含命令、子代理、钩子、技能、MCP 配置。

18.1 安装

bash 复制代码
# 从官方市场
claude plugin install code-review@claude-plugins-official

# 列出
claude plugin list

# 卸载
claude plugin remove code-review

18.2 临时加载本地插件

bash 复制代码
claude --plugin-dir ./my-plugins --plugin-dir ../shared-plugins

18.3 重载(不重启会话)

复制代码
/reload-plugins

推荐看 awesome-claude-code 找现成插件。


19. Git 工作流:分支、Worktree、PR

Claude Code 把 Git 对话化了。

19.1 日常 Git

复制代码
what files have I changed?
diff src/auth.ts vs main
commit my changes with a descriptive message
create a new branch called feature/login-redesign
rebase onto main and resolve conflicts

19.2 Worktree 并行

--worktree<repo>/.claude/worktrees/<n> 起一个独立工作树,主仓库不受影响

bash 复制代码
claude -w feature-auth
claude -w bug-fix-2031 --tmux       # 用 tmux 分屏

19.3 PR 自动化

bash 复制代码
# 创建 PR(需 gh CLI)
> create a PR titled "fix: login race condition" with a summary of the changes

# 让 Claude 监视 PR,CI 失败自动修
/autofix-pr

# 安全审查
/security-review

--from-pr 可恢复绑定到某 PR 的会话:

bash 复制代码
claude --from-pr 123
claude --from-pr https://github.com/org/repo/pull/123

19.4 远程派单:/batch

把一个大任务拆为多个并行子任务,每个走独立 worktree、各自起子 agent 实现并开 PR:

复制代码
/batch migrate src/components/ from class components to hooks

Claude 会先列出 5--30 个独立单元供你审,确认后并行展开。


20. Headless / 脚本化使用(-p 模式)

-p--print)让 Claude Code 不进入交互,跑完输出后退出,便于在脚本和流水线里嵌入。

20.1 基本

bash 复制代码
# 单次查询
claude -p "explain this function" < src/utils.ts

# 输出 JSON
claude -p "list TODOs in src/" --output-format json

# 流式 JSON
claude -p "refactor src/api.ts to async" --output-format stream-json --include-partial-messages

# 限制 turns 与预算
claude -p "fix the failing tests" --max-turns 10 --max-budget-usd 2.00

20.2 结构化输出

bash 复制代码
claude -p "extract all TODO comments from src/" \
  --output-format json \
  --json-schema '{
    "type":"array",
    "items":{
      "type":"object",
      "properties":{"file":{"type":"string"},"line":{"type":"integer"},"text":{"type":"string"}},
      "required":["file","line","text"]
    }
  }' > todos.json

20.3 极简启动 --bare

跳过 hooks/skills/plugins/MCP/CLAUDE.md 自动发现,启动最快,适合 cron 任务:

bash 复制代码
claude --bare -p "summarize git log of the last 24h" > daily-digest.md

20.4 流水线管道

bash 复制代码
# 让 Claude 解释错误日志
docker logs my-app --since 1h | claude -p "summarize the errors and propose fixes"

# 多阶段
git diff main...HEAD | claude -p --output-format json "list risky changes" \
  | jq '.[] | select(.risk=="high")'

21. IDE 集成(VS Code 与 JetBrains)

21.1 VS Code

在 Extensions Marketplace 搜索 Claude Code 安装,然后:

  • 打开 Claude Code 面板(侧边栏)
  • 编辑器里选中代码 → 右键 / 命令面板 → 询问 Claude
  • claude --ide 让终端 Claude 自动连上当前 VS Code

VS Code 集成自动启用:

  • Diff 查看器复用 VS Code 原生 UI
  • 跨编辑器 / 终端的选区共享
  • 调试器集成

21.2 JetBrains 系(IntelliJ、PyCharm、WebStorm 等)

在 Plugins Marketplace 搜索 Claude Code 安装。功能类似 VS Code 插件。

21.3 Shift+Enter 等快捷键

在 VS Code 内置终端、Alacritty、Warp 等终端内运行:

复制代码
/terminal-setup

22. Web、桌面、Slack、移动端多形态

形态 说明
Terminal CLI 主形态,本教程主体
Claude Code on the Web https://claude.ai/code,浏览器里跑同样的 agent
Desktop App macOS / Windows 桌面 App,/desktop 把当前会话搬过去
Slack App /install-slack-app 一键安装;在 Slack 里 @Claude
GitHub App /install-github-app 安装,PR 评论里 @claude 触发
Mobile App /mobile 出二维码下载 iOS / Android

22.1 Remote Control:从 claude.ai 控制本地终端

让你在浏览器里从 claude.ai 直接驱动本地的 Claude Code 会话:

bash 复制代码
claude remote-control --name "My Project"
# 或在已有会话内
/remote-control

22.2 Teleport:把 Web 会话拉回本地

在 Web 上跑了一会儿想转到本地继续:

bash 复制代码
claude --teleport
# 会话内
/teleport

23. CI/CD 集成(GitHub Actions、GitLab CI)

23.1 GitHub Actions

最便捷的方式是装官方 GitHub App:/install-github-app。之后在 PR 评论里 @claude please review this PR for security issues 即可触发。

也可在 workflow 里用:

yaml 复制代码
# .github/workflows/claude-review.yml
name: Claude Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Claude Code
        run: curl -fsSL https://claude.ai/install.sh | bash
      - name: Run review
        env:
          CLAUDE_CODE_OAUTH_TOKEN: ${{ secrets.CLAUDE_TOKEN }}
        run: |
          claude -p "Review the diff for security and performance issues. \
                     Output findings as JSON." \
            --output-format json \
            --max-budget-usd 1.00 \
            --max-turns 10 > review.json

token 用 claude setup-token 生成。

23.2 GitLab CI

yaml 复制代码
claude_review:
  image: ubuntu:24.04
  before_script:
    - apt-get update && apt-get install -y curl git
    - curl -fsSL https://claude.ai/install.sh | bash
  script:
    - claude -p --max-budget-usd 1.00 "Review the diff" --output-format json
  variables:
    CLAUDE_CODE_OAUTH_TOKEN: $CLAUDE_TOKEN

24. 成本控制与用量监控

24.1 看用量

命令 显示
/cost 当前会话 token 用量
/usage 计划余量与速率限制
/stats 历史用量、连续天数、模型偏好

24.2 预算硬限

-p 模式:

bash 复制代码
claude -p --max-budget-usd 5.00 --max-turns 20 "..."

24.3 省钱套路

  1. 默认 Sonnet,必要时 Opus:日常 Sonnet 4.6 完全够用,复杂规划/调试再切 Opus
  2. 小任务用 Haiku:批量改 import、重命名、加注解、写注释
  3. 大任务派子代理 :用 /batch 让多个 Haiku worker 并行做,主会话用 Opus 编排
  4. /clear 重置:换任务前清空,免得拖着无关上下文
  5. /compact:长会话压缩,保留要点
  6. --bare:脚本场景跳过自动发现,节省启动成本
  7. --exclude-dynamic-system-prompt-sections:多用户场景提升 prompt 缓存复用

24.4 速率限制

/extra-usage 配置额度耗尽后是否切到按量付费。


25. 最佳实践

25.1 Prompt 写法

不好
fix the bug fix the login bug where users see a blank screen after entering wrong credentials. The error happens in src/auth/login.ts. Add a regression test.
improve the code refactor src/api/users.ts to use async/await instead of callbacks. Keep the public API unchanged. Run pnpm test after.
explain this walk me through the data flow from app/api/checkout/route.ts to the database, including any middleware.

要点:

  • 具体到文件路径
  • 明确成功标准(测试通过、类型检查过、特定函数签名)
  • 复杂任务拆步骤

25.2 让 Claude 先探索再动手

复制代码
1. analyze the auth module structure first
2. propose 2-3 refactoring strategies with trade-offs
3. wait for me to pick one before changing any code

25.3 Plan 模式更安全

复杂改动用 /plan--permission-mode plan,让 Claude 先出方案。

25.4 用 CLAUDE.md 沉淀约定

每次发现 Claude 犯同一错误(比如老用 npm 而不是 pnpm),就把矫正写进 CLAUDE.md

25.5 用 hooks 守护

  • 编辑后自动 prettier/ruff format
  • git push 前扫描密钥
  • Bash 前禁 rm -rf / curl | sh

25.6 用 Skills 沉淀领域知识

把「公司付款逻辑」「API 网关约定」「数据库迁移流程」等业务知识写成 skill,避免每次重复教 Claude。

25.7 大任务用 /batch 与 worktree

跨 30 个文件的迁移、几十个组件的重构 --- 不要一个会话硬扛,用 /batch 派并行子代理。

25.8 高风险路径加 deny 规则

jsonc 复制代码
"deny": [
  "Edit(.env*)",
  "Edit(prisma/migrations/**)",
  "Bash(rm -rf:*)",
  "Bash(git push --force*)",
  "Bash(curl:* | sh)"
]

25.9 团队协作

  • .claude/settings.jsonCLAUDE.md 提交到 git,团队共享
  • .claude/settings.local.jsonCLAUDE.local.md git 忽略
  • /team-onboarding 自动生成新成员入门指南

26. 常见问题与排查

26.1 安装/启动问题

现象 解决
command not found: claude 重开 shell 让 PATH 生效;或检查安装方式(npm 安装已废弃)
Windows 'irm' is not recognized 你在 CMD 里,需在 PowerShell 跑 irm ...
Windows The token '&&' is not a valid statement separator 你在 PowerShell 里,需在 CMD 跑
Alpine 报缺库 apk add libgcc libstdc++ ripgrep 然后 export USE_BUILTIN_RIPGREP=0
自动更新失效 Homebrew/WinGet 安装的不会自动更新,要手动 brew upgrade / winget upgrade

26.2 登录问题

现象 解决
反复要求登录 claude auth status --text 看真实状态;/logout 后重新 /login
切账号 /login 即可,无需手动清凭据
凭据存哪 macOS Keychain / Linux Secret Service / Windows Credential Manager

26.3 行为问题

现象 解决
Claude 老是问权限 把常用命令加进 permissions.allow,或用 --permission-mode acceptEdits
上下文太长变慢 /compact/clear
改错地方了 /rewind 倒回;或 git restore
想看花了多少 /cost/usage/stats
Hook 没触发 claude --debug "hooks" 看日志,确认 matcher 正确
MCP 连不上 /mcp 看状态,触发 OAuth;查 token 是否过期

26.4 万能急救

复制代码
/doctor     # 自检并按 f 让 Claude 修
/feedback   # 实在不行就提 bug

26.5 调试

bash 复制代码
claude --debug              # 全开
claude --debug "api,hooks"  # 仅这两类
claude --debug "!statsig"   # 排除指定类
claude --debug-file /tmp/claude.log

27. 完整示例:从零开始的真实工作流

下面演示「从一个空仓库到完成一个有测试、有 CI、有审查的 PR」全流程。

步骤 1:初始化项目并让 Claude 看一眼

bash 复制代码
mkdir todo-api && cd todo-api
git init
pnpm init -y

claude

会话内:

复制代码
This will be a TypeScript Node.js TODO API using Fastify and SQLite.
Set up the project: tsconfig (strict), eslint, prettier, vitest, fastify, better-sqlite3, zod.
Then create CLAUDE.md documenting conventions and useful commands.

Claude 会装依赖、写配置、生成 CLAUDE.md

步骤 2:让 Claude 先规划再动手

复制代码
/plan implement CRUD endpoints for todos with input validation and tests

审完计划后按 Esc/Tab 退出 plan,让它执行。

步骤 3:边写边测

复制代码
run the tests and fix anything that fails
add tests for edge cases: empty title, super long title, missing fields

步骤 4:加配置文件让以后更省心

.claude/settings.json

jsonc 复制代码
{
  "model": "claude-sonnet-4-6",
  "permissions": {
    "allow": [
      "Bash(pnpm test:*)",
      "Bash(pnpm lint:*)",
      "Bash(pnpm typecheck:*)",
      "Bash(git diff:*)",
      "Bash(git log:*)",
      "Bash(git status:*)",
      "Read",
      "Edit"
    ],
    "deny": [
      "Edit(.env*)",
      "Bash(rm -rf:*)",
      "Bash(curl:* | sh)"
    ]
  },
  "hooks": {
    "PostToolUse": [
      {
        "matcher": { "tool": "Edit", "filePattern": "*.ts" },
        "command": "pnpm prettier --write \"$CLAUDE_HOOK_FILE\""
      }
    ]
  }
}

步骤 5:起一个分支并并行加功能

bash 复制代码
claude -w feature-tags

会话内:

复制代码
Add a "tags" feature: each todo can have multiple tags.
- DB migration
- API endpoints to filter by tag
- Tests for the new behavior
- Update README

步骤 6:开 PR 并自动修

复制代码
create a PR titled "feat: tag support for todos" with a summary

/autofix-pr
/security-review

步骤 7:合并后清理

复制代码
/clear
checkout main and pull. delete the merged branch.

至此,一个完整的「项目初始化 → 计划 → 实现 → 测试 → PR → 审查 → 合并」工作流跑完。


28. 参考链接汇总

官方文档

仓库与社区

状态与支持

相关推荐
网瘾新之助8 小时前
Claude Code 最佳实战指南
claude
易安说AI19 小时前
Claude Code 从零上手:国内用户保姆级安装教程
claude
冬奇Lab19 小时前
Claude Code 接入 SonarQube 静态扫描:AI 写代码,质量闭环了
人工智能·ai编程·claude
冬奇Lab19 小时前
一天一个开源项目(第84篇):free-claude-code —— 零费用运行 Claude Code 的代理黑魔法
人工智能·开源·claude
易安说AI1 天前
万字讲透Agent Harness的十二大模块
claude
刻意思考1 天前
Claude Code导览
claude
搞Ai的小月月1 天前
Claude Code + dbskill 零基础安装指南:从环境准备到 API 接入
api·claude
存在X1 天前
claude code自定义模型
前端·claude