Some content in this article was created with AI assistance. Please verify as needed.

Claude Code 是 Anthropic 官方的终端型 coding agent。它在本地项目目录里运行,可以读代码、改文件、执行命令,也能通过 CLAUDE.md、settings、slash commands、MCP、hooks 这些机制适配项目工作流。

这里先只记官方 Claude Code 的基本用法。第三方 Anthropic-compatible API 的接入放到 API 那篇里。

安装和启动

官方快速开始要求 Node.js 18 或更新版本,登录用 Claude.ai 账号或 Anthropic Console 账号。

1
2
3
npm install -g @anthropic-ai/claude-code
cd your-project
claude

第一次运行 claude 按提示登录即可。我一般在 Git 仓库根目录启动,省得上下文和可写范围混乱。

常用命令

1
2
3
4
5
6
claude
claude --version
claude config list
claude config get <key>
claude config set <key> <value>
claude config set -g <key> <value>

claude config 默认修改项目配置;加 -g / --global 修改用户级全局配置。

settings.json

settings.json 用来配权限、环境变量和工具行为。

常用位置:

  • ~/.claude/settings.json:用户级配置,作用于所有项目。
  • .claude/settings.json:项目共享配置,可以提交到仓库。
  • .claude/settings.local.json:项目本地个人配置,不应提交。
  • 企业托管配置:由组织在系统位置统一下发,优先级最高。

配置优先级从高到低:

1
2
3
4
5
Enterprise managed policies
Command line arguments
Local project settings
Shared project settings
User settings

常见配置示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"permissions": {
"allow": [
"Bash(npm run lint)",
"Bash(npm run test:*)"
],
"deny": [
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)"
]
},
"env": {
"BASH_DEFAULT_TIMEOUT_MS": "120000"
}
}

敏感文件最好直接用 permissions.deny 藏掉,不要只靠口头提醒 agent “不要读”。

CLAUDE.md memory

CLAUDE.md 是 Claude Code 的 memory 文件,适合放项目说明、常用命令、代码风格和长期偏好。

常见位置:

  • ~/.claude/CLAUDE.md:用户 memory,只对自己生效。
  • ./CLAUDE.md:项目 memory,适合随仓库共享。
  • 企业级 CLAUDE.md:组织统一下发。

初始化项目 memory:

1
/init

编辑 memory:

1
/memory

也可以在输入中用 # 快速添加一条 memory,然后按提示选择写入位置。

适合写入 CLAUDE.md 的内容:

  • 常用 build / test / lint 命令。
  • 项目架构和目录约定。
  • 命名、代码风格、测试约定。
  • 只对该项目长期成立的注意事项。

不要写入 API key、token、私有代理账号或一次性任务提示。

slash commands

Claude Code 的交互命令以 / 开头。我常看的主要是:

  • /help:查看帮助。
  • /status:查看账号和系统状态。
  • /config:查看或修改配置。
  • /permissions:查看或更新权限。
  • /model:选择或切换模型。
  • /clear:清空当前会话历史。
  • /compact:压缩上下文。
  • /memory:编辑 memory 文件。
  • /mcp:管理 MCP 连接。
  • /review:请求代码审查。

自定义 slash command 本质上是 Markdown 文件:

1
2
.claude/commands/<command-name>.md
~/.claude/commands/<command-name>.md

项目级 command 可以提交给团队共享,用户级 command 适合个人常用 prompt。命令名来自文件名,例如 .claude/commands/security-review.md 对应 /security-review

权限和工具

Claude Code 可以读文件、搜索、编辑、执行 shell,也有 WebFetch、WebSearch、Notebook 等工具。读文件和搜索通常比较低风险,编辑、写文件、执行命令、联网这些则要看权限规则。

我的基本做法:

  • 项目共享配置中允许稳定的检查命令,例如 lint、test。
  • 明确 deny .env、secrets、credentials、部署凭据。
  • curl、发布命令、删除命令、云服务命令保持默认询问或禁止。
  • 不把 API key 写进 .claude/settings.jsonCLAUDE.md

排查顺序

  1. 用官方登录方式确认 Claude Code 本身可用。
  2. /status 检查账号、模型和系统状态。
  3. /doctor 检查安装健康状态。
  4. 检查 settings.json 是否覆盖了权限或环境变量。
  5. 检查 CLAUDE.md 是否包含过期命令或冲突说明。
  6. 权限问题优先看 /permissionspermissions.deny / permissions.allow

非交互式运行

下面整理一下 Claude Code 的非交互模式用法。和 Codex CLI 中的 codex exec 类似,Claude Code 也可以在命令行中执行一次性任务,然后直接退出。

Claude Code 的非交互模式主要通过 -p / --print 启用。例如:

1
claude -p "summarize this repository"

在这种模式下,Claude Code 会执行这条 prompt,然后把结果输出到终端并退出。它适合脚本、CI、pre-commit hook、日志分析、批处理等场景。

最基本的用法是直接加上一段提示词:

1
claude -p "What does this project do?"

在默认情况下,输出格式是普通文本,因此可以像普通命令行工具一样重定向或接入管道。例如:

1
claude -p "summarize this repository" > summary.md

也可以把命令输出、日志、diff 等内容通过 stdin 传给 Claude Code,然后直接把结果写入文件:

1
2
3
cat build-error.txt | claude -p "concisely explain the root cause of this build error" > output.txt

git diff main | claude -p "review this diff and list possible issues"

此时命令行中的字符串是任务指令,stdin 中的内容则作为附加上下文传给 Claude Code。这种用法很适合总结测试输出、编译错误、lint 结果、git diff 等。

需要注意的是,Claude Code 对 piped stdin 有大小限制。对于很大的输入,不建议直接 pipe;更稳妥的方式是把内容保存到文件里,然后在 prompt 中让 Claude 读取或参考对应文件。

输出方面,Claude Code 的 --output-format 选项比较重要。它可以指定非交互模式下的输出格式:

1
2
3
claude -p "summarize this repository" --output-format text
claude -p "summarize this repository" --output-format json
claude -p "summarize this repository" --output-format stream-json

其中 text 是默认格式,也就是普通文本输出。

如果需要实时事件流,可以使用 --output-format stream-json。这个模式会输出 JSON lines,也就是每一行都是一个 JSON 对象,适合调试、CI 日志、实时 UI 或程序化处理。

例如:

1
claude -p "Explain recursion" --output-format stream-json

如果使用 --output-format json,输出会变成一个结构化 JSON 对象,其中包含文本结果、session ID、usage、cost 等元信息。文本回答通常在 result 字段中,可以配合 jq 提取。

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

--output-format json 和要求最终回答是某个特定 JSON 结构不是一回事。前者是 Claude Code 外层返回格式,里面会包含 metadata;后者还需要使用 --json-schema 来约束最终结构化结果。
此时返回的 JSON 仍然包含 session ID、usage 等外层信息,而符合 schema 的结构化结果会放在 structured_output 字段中,可以用 jq 提取。

例如

1
2
3
4
claude -p "Extract project metadata" \
--output-format json \
--json-schema '{"type":"object","properties":{"name":{"type":"string"},"language":{"type":"string"}},"required":["name"]}' \
| jq '.structured_output'

关于输入格式,Claude Code 也支持 --input-format,但是常见情况下不需要显式设置,默认文本输入已经够用。如果需要以事件流方式输入,可以使用:

1
claude -p --input-format stream-json --output-format stream-json

这更适合 SDK / 程序集成场景。

为了让脚本启动更快、结果更可控,Claude Code 官方推荐在脚本或 CI 中考虑使用 --bare

1
claude --bare -p "summarize this repository"

--bare 会跳过 hooks、skills、plugins、MCP servers、auto memory、CLAUDE.md 等自动发现内容。也就是说,它不会像普通交互式 Claude Code 那样加载当前项目和用户目录中的各种配置。这样做的好处是启动更快,也更适合 CI 和脚本,因为不同机器上的本地配置不容易影响结果。

如果在 --bare 模式下仍然需要某些额外上下文或配置,也可以显式传入。

关于权限,Claude Code 非交互模式下最需要注意的是:如果任务需要读文件、改文件、运行命令,就必须提前考虑工具权限,否则运行到需要确认的地方可能会中断或失败。

可以使用 --allowedTools 预批准某些工具。例如,只允许读取文件:

1
claude -p "summarize this repository" --allowedTools "Read"

如果希望它可以读取、编辑文件,并运行命令,可以写成:

1
2
claude -p "Run the test suite and fix any failures" \
--allowedTools "Bash,Read,Edit"

更细粒度地,也可以只允许特定 Bash 命令:

1
2
claude -p "look at staged changes and create a commit message" \
--allowedTools "Bash(git diff *),Bash(git status *),Bash(git log *)"

需要注意的是,--allowedTools 使用的是权限规则语法。比如 Bash(git diff *) 中的空格和 * 表示前缀匹配,意思是允许以 git diff 开头的命令。

除了列出具体工具,也可以使用 --permission-mode 设置本次运行的权限模式。例如:

1
claude -p "apply lint fixes" --permission-mode acceptEdits

常见的 permission mode 包括:

  • default:默认模式,主要允许读取,敏感操作需要确认。
  • acceptEdits:允许读文件、编辑文件,以及一些常见文件系统操作。
  • plan:主要用于先分析和制定计划,不直接修改。
  • auto:允许更多操作,但有后台安全检查。
  • dontAsk:只允许预先批准的工具,适合更锁定的 CI / 脚本环境。
  • bypassPermissions:跳过大部分权限提示,只建议在隔离容器、VM 或专门 runner 中使用。

如果是自动化脚本,通常更推荐显式列出 --allowedTools,或者使用较保守的 --permission-mode dontAsk。如果是在本地临时跑一次改代码任务,acceptEdits 会比较方便。bypassPermissions 风险更高,不应该在普通工作区里随便使用。

还可以用 --disallowedTools 显式禁止某些工具或命令。例如:

1
2
3
claude -p "review this repository" \
--allowedTools "Read,Bash" \
--disallowedTools "Bash(rm *)"

对于长任务,可以用 --max-turns 限制 agentic turns,避免无限展开:

1
claude -p "review this codebase for obvious bugs" --max-turns 3

如果使用 API 计费,也可以用 --max-budget-usd 限制本次调用的预算:

1
claude -p "analyze this repository" --max-budget-usd 5.00

模型方面,可以用 --model 指定本次运行使用的模型:

1
claude -p "review this diff" --model sonnet

也可以使用完整模型名:

1
claude -p "review this diff" --model claude-sonnet-4-6

如果需要继续之前的对话,可以使用 --continue--resume

--continue 会继续当前目录下最近的 conversation:

1
2
3
claude -p "Review this codebase for performance issues"
claude -p "Now focus on database queries" --continue
claude -p "Generate a summary of all issues found" --continue

如果有多个 session,更稳妥的方式是先用 JSON 输出捕获 session_id,然后用 --resume 精确恢复:

1
2
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"

如果不希望本次非交互运行被保存到本地 session 历史中,可以使用 --no-session-persistence

1
claude -p "summarize this repository" --no-session-persistence

这个选项适合一次性脚本、CI 或不需要后续 resume 的任务。

如果需要定制系统提示词,可以使用 --append-system-prompt,在保留 Claude Code 默认行为的基础上追加规则:

1
2
3
git diff main | claude -p \
--append-system-prompt "You are a careful code reviewer. Focus on correctness and security." \
"review this diff"

也可以从文件读取追加提示:

1
2
claude -p "review this repository" \
--append-system-prompt-file ./review-rules.txt

更强的做法是用 --system-prompt--system-prompt-file 完全替换默认系统提示词:

1
2
claude -p "classify these logs" \
--system-prompt "You are a log classification tool. Return only the classification."

不过完全替换默认 system prompt 会丢掉 Claude Code 默认的代码助手身份、工具使用约定和安全提示,所以普通开发任务一般优先使用 --append-system-prompt

在 CI 或自动化环境中,认证也需要注意。Claude Code 可以使用已有登录状态;如果设置了 ANTHROPIC_API_KEY,在非交互模式下会优先使用这个 API key。例如:

1
ANTHROPIC_API_KEY=... claude --bare -p "summarize this repository"

如果是 CI,通常不建议把 API key 暴露给整个 job 的所有步骤;更稳妥的做法是只在调用 Claude Code 的那一步提供凭据。

一个比较典型的 CI / 脚本调用形式是:

1
2
3
4
git diff main | ANTHROPIC_API_KEY=... claude --bare -p \
"review this diff and report only serious correctness issues" \
--output-format json \
--allowedTools "Read"

参考