Claude Code 使用指南:从安装配置到高级自动化
Claude Code 是一款基于终端的 AI 编程助手,支持代码生成、审查与自动化任务。涵盖安装配置、环境变量设置、命令用法及子代理功能。重点介绍了 MCP 协议集成、钩子系统(Hooks)实现自定义逻辑,以及 GitHub Actions 中的自动化工作流。同时包含安全最佳实践、权限管理及性能优化建议,帮助开发者高效利用 AI 提升开发效率。

Claude Code 是一款基于终端的 AI 编程助手,支持代码生成、审查与自动化任务。涵盖安装配置、环境变量设置、命令用法及子代理功能。重点介绍了 MCP 协议集成、钩子系统(Hooks)实现自定义逻辑,以及 GitHub Actions 中的自动化工作流。同时包含安全最佳实践、权限管理及性能优化建议,帮助开发者高效利用 AI 提升开发效率。

Enable sound alerts when claude completes the task:
claude config set --global preferredNotifChannel terminal_bell
Send
claudeornpx claudein terminal to start the interface Go to Help & Troubleshooting to fix issues…
# Node.js 18+ (Universal Method)
npm install -g @anthropic-ai/claude-code
# Windows (CMD)
npm install -g @anthropic-ai/claude-code
# Windows (PowerShell)
irm https://claude.ai/install.ps1 | iex
# WSL/Git
npm install -g @anthropic-ai/claude-code
# MacOS
brew install node && npm install -g @anthropic-ai/claude-code
# Linux
sudo apt update && sudo apt install -y nodejs npm
npm install -g @anthropic-ai/claude-code
# Arch
yay -S claude-code
# Docker
# Windows (CMD)
docker run -it --rm -v "%cd%:/workspace" -e ANTHROPIC_API_KEY="sk-your-key" node:20-slim bash -lc "npm i -g @anthropic-ai/claude-code && cd /workspace && claude"
# macOS/Linux (bash/zsh)
docker run -it --rm -v "$PWD:/workspace" -e ANTHROPIC_API_KEY="sk-your-key" node:20-slim bash -lc 'npm i -g @anthropic-ai/claude-code && cd /workspace && claude'
# Check installation
which claude # Linux
where claude # Windows
claude --version # Universal
# Common Management
claude config # Configure settings
claude mcp list # Setup MCP servers
claude /agents # Configure Subagents
claude update # Update to latest
Open Project Via Terminal Into VS Code / Cursor:
cd /path/to/project code .
Make sure you have the Claude Code extension installed in your VS Code / Cursor.
Find API key from Anthropic Console. Do NOT commit real keys; use git-ignored files, OS key stores, or secret managers.
# Universal
claude /login
claude setup-token
# Windows
set ANTHROPIC_API_KEY=sk-your-key-here-here
setx ANTHROPIC_API_KEY "sk-your-key-here-here"
# Linux
export ANTHROPIC_API_KEY="sk-your-key-here-here"
unset ANTHROPIC_API_KEY
# PowerShell
$env:ANTHROPIC_API_KEY = "sk-your-key-here-here"
[Environment]::SetEnvironmentVariable("ANTHROPIC_API_KEY","sk-your-key-here-here","User")
# Persist Bash/Zsh/Fish
echo 'export ANTHROPIC_API_KEY="sk-your-key-here-here"' >> ~/.bashrc && source ~/.bashrc
echo 'export ANTHROPIC_API_KEY="sk-your-key-here-here"' >> ~/.zshrc && source ~/.zshrc
fish -lc 'set -Ux ANTHROPIC_API_KEY sk-your-key-here-here'
You can also set any of these in settings.json under the 'env' key for automatic application.
Windows Users replace export with set or setx for permanent changes.
export ANTHROPIC_API_KEY="sk-your-key-here-here"
export ANTHROPIC_AUTH_TOKEN="my-auth-token"
export ANTHROPIC_MODEL="claude-sonnet-4-20250514"
export BASH_DEFAULT_TIMEOUT_MS=60000
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096
export DISABLE_TELEMETRY=0
export HTTP_PROXY="http://proxy:8080"
export HTTPS_PROXY="https://proxy:8443"
claude config set-g theme dark
claude config set-g preferredNotifChannel iterm2_with_bell
claude config set-g autoUpdates true
claude config set-g verbose true
claude config set-g includeCoAuthoredBy false
claude config set-g model "claude-3-5-sonnet-20241022"
claude config set-g enableAllProjectMcpServers true
claude config set-g enabledMcpjsonServers '["memory","github"]'
claude config set-g disabledMcpjsonServers '["filesystem"]'
Claude Code offers four memory locations in a hierarchical structure:
| Memory Type | Location | Purpose |
|---|---|---|
| Enterprise policy | /Library/Application Support/ClaudeCode/CLAUDE.md (macOS) | Organization-wide instructions managed by IT/DevOps |
| Project memory | ./CLAUDE.md | Team-shared instructions for the project |
| User memory | ~/.claude/CLAUDE.md | Personal preferences for all projects |
| Project memory (local) | ./CLAUDE.local.md | Personal project-specific preferences |
All memory files are automatically loaded into Claude Code's context when launched. Files higher in the hierarchy take precedence.
| Command | Purpose |
|---|---|
/add-dir | Add additional working directories |
/agents | Manage custom AI subagents |
/bug | Report bugs |
/clear | Clear conversation history |
/compact | Compact conversation |
/config | View/modify configuration |
/cost | Show token usage statistics |
/doctor | Checks health of installation |
/help | Get usage help |
/init | Initialize project with CLAUDE.md |
/login | Switch Anthropic accounts |
/mcp | Manage MCP server connections |
/memory | Edit CLAUDE.md memory files |
/model | Select or change the AI model |
/permissions | View or update tool permissions |
/review | Request code review |
/vim | Enter vim mode |
| Flag / Command | Description |
|---|---|
-d, --debug | Enable debug mode |
--verbose | Override verbose mode setting |
-p, --print | Print response and exit |
--output-format <format> | Output format (text, json, stream-json) |
--allowedTools | Comma/space-separated list of allowed tools |
--disallowedTools | List of denied tools |
--mcp-config | Load MCP servers from JSON files |
--permission-mode | Permission mode for the session |
--model <model> | Model for the current session |
--continue | Continue most recent conversation |
--dangerously-skip-permissions | Bypass all permission checks |
# Basics
claude # Start interactive REPL
claude "explain this project" # Start REPL seeded with prompt
claude -p "summarize README.md" # Non-interactive print mode
cat logs.txt | claude -p "explain" # Pipe input to Claude
# Update & Install
claude update
claude doctor
claude migrate-installer
# Config
claude config get <key>
claude config set <key> <val>
claude config add <key> <vals…>
claude config remove <key> <vals…>
claude config list
# MCP Management
claude mcp list
claude mcp add <name> <command>
claude mcp remove <name>
# Other useful flags
claude --add-dir ../apps ../lib
claude --allowedTools "Bash(git log:*)" "Read"
claude --dangerously-skip-permissions
| Shortcut | Description |
|---|---|
Ctrl+C | Cancel current input or generation |
Ctrl+D | Exit Claude Code session |
Ctrl+L | Clear terminal screen |
Up/Down arrows | Navigate command history |
Esc + Esc | Edit previous message |
| Method | Shortcut |
|---|---|
| Quick escape | \ + Enter |
| macOS default | Option+Enter |
| Terminal setup | Shift+Enter |
| Control sequence | Ctrl+J |
Enable vim-style editing with
/vimcommand or configure permanently via/config.
| Command | Action |
|---|---|
Esc | Enter NORMAL mode |
i | Insert before cursor |
a | Insert after cursor |
o | Open line below |
| Command | Action |
|---|---|
h/j/k/l | Move left/down/up/right |
w/e/b | Word navigation |
gg/G | Beginning/End of input |
| Command | Action |
|---|---|
x/dd/D | Delete character/line/end of line |
cc/C | Change line |
. | Repeat last change |
Claude Code maintains command history for the current session:
/clear commandCtrl+R: Reverse search through history (if supported)!) is disabled by defaultGives Claude extra pre-answer planning time by adding ONE of these keywords to your prompt.
Examples:
claude -p "Think. Outline a plan to refactor the auth module."
claude -p "Think harder. Draft a migration plan from REST to gRPC."
claude -p "Ultrathink. Propose a step-by-step strategy to fix flaky payment tests."
Sub‑Agents are purpose‑built helpers with their own prompts, tools, and isolated context windows.
Example prompt (tester.prompt.md):
Role: Write a single, focused failing test for the specific scenario I describe.
Scope: Only create/modify tests under tests/. Do not change src/.
Output: A brief rationale + a unified diff or patch.
MCP extends Claude's capabilities by connecting to external services, databases, APIs, and tools.
Basic MCP Commands:
claude mcp # Interactive MCP configuration
claude mcp list # List configured servers
claude mcp add <name> <cmd> # Add new server
claude mcp remove <name> # Remove server
Configuration File Location:
~/.claude.json - Global File.mcp.json - Project-scoped serversPopular MCP Servers:
git-mcp-server, github-mcp-serverpostgres-mcp-server, mysql-mcp-serverclaude --allowedTools "mcp__git__commit,mcp__git__push"
claude --allowedTools "Edit,View,mcp__git__*"
Hooks allow implementing custom logic based on events.
Hooks are configured in settings files:
~/.claude/settings.json - User settings.claude/settings.json - Project settings.claude/settings.local.json - Local project settingsStructure:
{
"hooks": {
"EventName": [
{
"matcher": "ToolPattern",
"hooks": [{"type": "command", "command": "your-command-here"}]
}
]
}
}
PreToolUse: Runs before processing a tool call.PostToolUse: Runs immediately after a tool completes.Notification: Runs when Claude needs permission or is idle.UserPromptSubmit: Runs when user submits a prompt.Stop: Runs when agent finishes responding.SessionStart: Runs when starting a new session.USE AT YOUR OWN RISK: Claude Code hooks execute arbitrary shell commands on your system automatically. By using hooks, you acknowledge that you are solely responsible for the commands you configure.
Always review and understand any hook commands before adding them to your configuration.
NEVER use in Production systems, shared machines, or any systems with important data. Only use with isolated environments like a Docker container.
claude --dangerously-skip-permissions
~/.claude.json private (chmod 600).--strict-mcp-config to only load MCP servers from specified config files.GitHub Actions integration allows automated reviews and triage.
File: .github/workflows/claude-pr-auto-review.yml
name: Auto review PRs
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
jobs:
auto-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Claude PR review
uses: anthropics/claude-code-action@main
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
direct_prompt: |
Review this pull request's diff for correctness, readability, testing, performance, and DX.
allowed_tools: >-
mcp__github__get_pull_request_diff,
mcp__github__create_pending_pull_request_review,
mcp__github__add_comment_to_pending_review,
mcp__github__submit_pending_pull_request_review
File: .github/workflows/claude-issue-triage.yml
name: Claude Issue Triage
on:
issues:
types: [opened, edited, reopened]
jobs:
triage:
runs-on: ubuntu-latest
env:
CLAUDE_MODEL: claude-3-5-sonnet-20241022
steps:
- name: Ask Claude for triage JSON
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
# Collect context and ask Claude
cat > payload.json << 'JSON'
{ "model": "${{ env.CLAUDE_MODEL }}", ... }
JSON
curl -s https://api.anthropic.com/v1/messages ...
Check the output of claude doctor for log locations and environment checks.
Your PATH likely doesn't include the global npm bin directory.
C:\Users\<you>\AppData\Roaming\npmC:\Program Files\nodejs$(npm config get prefix)/binPath → Edit → New add:
C:\Users\<you>\AppData\Roaming\npmC:\Program Files\nodejswhere claudeclaude doctorMust be Node 18+ (20+ recommended).
node --version
npm uninstall -g @anthropic-ai/claude-code
npm install -g @anthropic-ai/claude-code
Verify your Anthropic API key is available to the CLI.
# PowerShell (Windows)
echo $env:ANTHROPIC_API_KEY
claude -p "test" --verbose
# bash/zsh (macOS/Linux)
echo $ANTHROPIC_API_KEY
claude -p "test" --verbose
Uninstall the global npm package and remove leftover files.
npm uninstall -g @anthropic-ai/claude-code
Remove-Item -LiteralPath "$env:USERPROFILE\.claude\downloads\*" -Recurse -Force
Remove-Item -LiteralPath "$env:USERPROFILE\.claude.json" -Force
npm install -g @anthropic-ai/claude-code
claude "Review UserAuth.js for security vulnerabilities...")claude "check my code")Tip: claude "query" starts the interactive REPL pre-seeded with your prompt; claude -p "query" runs print mode (non-interactive) and exits.
--model sonnet or --model opus).--add-dir ./services/api).claude config set-g cleanupPeriodDays 20).--max-turns 3).--output-format json).claude doctor..claude/settings.json to the repo.--dangerously-skip-permissions on production systems. Don't hard-code secrets.CLAUDE.md). Be specific in prompts.Have Claude Code installed:
npm install -g @anthropic-ai/claude-code
Config Environment Variables:
export ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic
export ANTHROPIC_AUTH_TOKEN=${YOUR_API_KEY}
export ANTHROPIC_MODEL=deepseek-chat
Now launch claude. Find more information from the Official Deepseek Docs.
Claude Code provides a powerful terminal-based interface for AI-assisted development. This guide covered installation, configuration, advanced features like Sub-Agents and Hooks, and integration with CI/CD pipelines. By following security best practices and optimizing prompts, developers can effectively leverage AI to enhance productivity and code quality.

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online