Part 4 of 10
用了几周 Claude Code 之后,我发现了一件事:我在反复输入同样的提示词。"检查这段代码的安全问题。""按项目规范生成测试。""写一条好的 commit 信息。"

每一次重复输入都是在浪费键盘寿命。自定义斜杠命令(Custom Slash Commands)能帮你搞定这个问题。
什么是自定义命令?
自定义命令就是 Markdown 文件,放对位置就能变成斜杠命令。比如你创建一个 review.md 文件,/review 就成了随时可用的命令。
.claude/commands/├── review.md → /review├── test.md → /test└── git/├── commit.md → /git:commit└── pr.md → /git:pr
精妙之处在于:这些命令可以接受参数,指定 Claude 能使用哪些工具,定义自动触发的钩子(Hooks),甚至强制使用某个特定模型。它们不只是保存好的提示词——而是可编程的工作流。
60 秒创建你的第一个命令
第一步:创建目录
mkdir -p .claude/commands
第二步:创建命令文件
cat > .claude/commands/review.md << 'EOF'Review the staged changes for:- Security vulnerabilities- Performance issues- Missing error handling- Type safety problemsFormat as: Critical (must fix) → Warnings → SuggestionsEOF
第三步:使用它
/review
搞定。Claude 会按你写的指令执行,就像你亲手打出来的一样。
参数:让命令活起来
静态命令挺实用,但动态命令才是真正的大杀器。$ARGUMENTS 占位符会捕获命令名后面的所有内容。
基础参数
# .claude/commands/explain.mdExplain how $ARGUMENTS works in this codebase.Show me the key files, the data flow, and any gotchas.
使用方式:
/explain the authentication system/explain the payment processing flow/explain how websockets connect to the backend
你在 /explain 后面输入的任何内容都会变成 $ARGUMENTS。
位置参数
需要更精确的控制?用 $1、$2、$3 指定具体位置:
# .claude/commands/fix-issue.mdFix GitHub issue #$1.Priority: $2Additional context: $31. Read the issue description2. Find the relevant code3. Implement the fix4. Write tests5. Create a commit referencing the issue
使用方式:
/fix-issue 1234 high "user reported login failures on mobile"
这里 $1 = "1234",$2 = "high",$3 = "user reported login failures on mobile"。
Frontmatter:命令的超能力
真正的大招来自命令文件顶部的 YAML frontmatter。它让你可以配置权限、提示、模型等等。
基础用法
---description: Review code for security issuesargument-hint: [file-or-directory]---Review $ARGUMENTS for security vulnerabilities including:- SQL injection- XSS- Authentication bypasses
description 会在运行 /help 时显示。argument-hint 告诉用户该传什么参数。
预授权工具权限
厌倦了每次都要批准相同的 git 命令?用 allowed-tools:
---description: Smart git commitallowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*), Bash(git diff:*)argument-hint: [optional message]---Analyze the staged changes and create a commit.If a message is provided, use it: $ARGUMENTSOtherwise, generate a descriptive message following conventional commits.Requirements:- Use format: type(scope): description- Keep summary under 72 characters- Body explains WHY, not WHAT
现在 /git:commit 在执行这些特定 git 命令时不会再弹出权限确认了。
强制使用指定模型
有些命令搭配特定模型效果更好:
---description: Deep architecture analysismodel: claude-sonnet-4-5-20250929---Analyze the architecture of $ARGUMENTS.Consider:- Design patterns in use- Coupling between modules- Scalability implications- Technical debt indicators
简单任务用 Haiku,常规任务用 Sonnet,复杂推理用 Opus:
---description: Quick code explanationmodel: claude-3-5-haiku-20241022---Briefly explain what $ARGUMENTS does in 2-3 sentences.
命令中的钩子
命令可以定义自己的钩子(Hooks),在执行过程中自动运行:
---description: Format and commithooks:PostToolUse:- matcher: "Edit|Write"hooks:- type: commandcommand: "npx prettier --write $FILE_PATH"---Make the requested changes to $ARGUMENTS.After each edit, files will be auto-formatted.
这会在每次文件编辑后自动运行 Prettier——但仅在这个命令激活时才会触发。
用目录做命名空间
把相关命令放在子目录里。文件夹名会变成命名空间(Namespace):
.claude/commands/├── git/│ ├── commit.md → /git:commit│ ├── pr.md → /git:pr│ ├── branch.md → /git:branch│ └── squash.md → /git:squash├── test/│ ├── unit.md → /test:unit│ ├── e2e.md → /test:e2e│ └── coverage.md → /test:coverage└── docs/├── readme.md → /docs:readme└── api.md → /docs:api
这样你的 /help 输出井井有条,命令也容易找到。
全局命令 vs 项目命令
项目命令(团队共享)
your-project/.claude/commands/
- 仅在当前项目可用
- 提交到 git——团队所有人都能用
- 适合项目特定的工作流
个人命令(仅限自己)
~/.claude/commands/
- 在所有项目中都可用
- 个人效率加速器
- 不会跟团队共享
推荐的分配方案
放全局(个人):
/explain— 通用代码解释/debug— 系统化调试流程/review— 通用代码审查清单
放项目(团队):
/deploy— 你的部署步骤/test:e2e— 你的测试配置/git:commit— 团队的 commit 规范/onboard— 给新成员看的项目上下文
10 个值得偷师的命令
这些都是实战验证过的命令。直接拿去用,改改,让它们成为你自己的。

1. /review — 代码审查
---description: Comprehensive code reviewargument-hint: [file or leave empty for staged changes]---Review $ARGUMENTS (or staged changes if not specified).## Check For- Security: OWASP Top 10, auth issues, data exposure- Performance: N+1 queries, memory leaks, blocking calls- Correctness: Edge cases, error handling, type safety- Maintainability: Complexity, naming, duplication## Output Format### 🚨 Critical (blocks merge)### ⚠️ Warnings (should fix)### 💡 Suggestions (nice to have)
2. /git:commit — 智能提交
---description: Analyze changes and create commitallowed-tools: Bash(git *)---1. Run `git diff --staged` to see changes2. Analyze what was changed and why3. Create a commit message:- Format: type(scope): description- Types: feat, fix, refactor, docs, test, chore- Under 72 chars- Body explains WHY if non-obvious4. Execute the commit
3. /test:generate — 测试生成
---description: Generate comprehensive testsargument-hint: [file-to-test]---Generate tests for $ARGUMENTS.## Include- Happy path (expected usage)- Edge cases (empty, null, boundaries)- Error scenarios (invalid input, failures)- Integration points (mocks for external deps)## Requirements- Match existing test patterns in this project- Use the testing framework already in use- Clear test names: "should [expected] when [condition]"
4. /debug — 系统化调试
---description: Debug an issue systematicallyargument-hint: [description of the problem]---Debug: $ARGUMENTS## Process1. Clarify: What's expected vs actual behavior?2. Reproduce: What triggers the issue?3. Isolate: Which component/function is responsible?4. Trace: Follow the data flow5. Fix: Implement and verify the solution## Output- Root cause- Affected code paths- Fix with explanation- Prevention strategy
5. /security — 安全审计
---description: Security vulnerability scanargument-hint: [file, directory, or leave empty for full scan]allowed-tools: Read, Grep, Glob---Audit $ARGUMENTS for security vulnerabilities.## Check For- Injection: SQL, command, XSS, template- Auth: Weak passwords, session issues, CSRF- Data: Exposure, logging secrets, insecure storage- Config: Debug mode, default creds, missing headers- Dependencies: Known CVEs## OutputSeverity-ranked findings with:- Location (file:line)- Risk explanation- Remediation steps
6. /refactor — 代码重构
---description: Refactor while maintaining behaviorargument-hint: [file-or-function]---Refactor $ARGUMENTS.## Goals- Reduce complexity- Improve readability- Apply DRY- Better naming- Smaller functions (single responsibility)## Constraints- NO behavior changes- Keep public API intact- Existing tests must passExplain each change.
7. /explain — 代码讲解
---description: Explain code for someone newargument-hint: [file, function, or concept]model: claude-3-5-haiku-20241022---Explain $ARGUMENTS.## Cover- What it does (purpose)- How it works (step by step)- Why it's designed this way- Dependencies and side effects- Potential gotchasAssume reader knows the language but not this codebase.
8. /optimize — 性能分析
---description: Analyze and optimize performanceargument-hint: [file-or-function]---Analyze $ARGUMENTS for performance.## Examine- Time complexity (Big O)- Space complexity- I/O operations- Database queries (N+1?)- Unnecessary allocations## Output- Current bottlenecks- Specific optimizations- Expected improvement- Trade-offs involved
9. /ship — 发布前检查清单
---description: Pre-deployment verificationallowed-tools: Bash(npm *), Bash(git *)---Pre-deploy checklist:- [ ] Tests pass (`npm test`)- [ ] Lint clean (`npm run lint`)- [ ] Build succeeds (`npm run build`)- [ ] No console.log/debugger statements- [ ] Env vars documented- [ ] No hardcoded secrets- [ ] Error handling complete- [ ] Migrations readyRun checks and report: Ready 🚀 or Blocked 🛑 with issues.
10. /catchup — 上下文恢复
这个命令实现了第2篇中介绍的 /clear + /catchup 模式,用于高效管理上下文。
---description: Rebuild context after /clearallowed-tools: Bash(git *)---I just cleared context. Help me catch up.1. Run `git diff main...HEAD --stat` to see what's changed2. Summarize the changes on this branch3. Read the key modified files4. Tell me where we likely are in this feature$ARGUMENTS (if any additional context)
超越代码:创意命令
命令不只是用来做代码工作流的。你可以整合 Claude 能调用的任何 API 或服务。这里有两个我在写这个博客系列时实际用到的:
/meme — 生成表情包
---description: Generate a meme using Imgflip APIargument-hint: "top text" "bottom text" [template]---Generate a meme using the Imgflip API.## API Details- Endpoint: https://api.imgflip.com/caption_image- Username: $IMGFLIP_USER- Password: $IMGFLIP_PASS## Popular Templates- drake (181913649) - Drake Hotline Bling- distracted (112126428) - Distracted Boyfriend- changemymind (129242436) - Change My Mind- twobuttons (87743020) - Two Buttons- pikachu (155067746) - Surprised Pikachu## Instructions1. Parse the arguments: $ARGUMENTS2. Use curl to POST to the API with template_id, text0, text13. Return the generated meme URL4. Download to ./public/assets/blog/ if requested
我用这个命令生成了第5篇里那个"男朋友看别的女生"表情包——开发者被"先上线再说"吸引,而"先写测试"在旁边投来不满的目光。
/imagen — AI 图片生成
这是我最爱的命令之一。Google 的 Imagen API 让你直接在 Claude Code 里生成图片。这是一个完整实现:
---description: Generate an image using Google Imagenargument-hint: "prompt" [output-path]allowed-tools: Bash(node *)---Generate an image using Google Imagen.## Instructions1. Parse the prompt from: $ARGUMENTS2. Run: node ~/.claude/scripts/generate-image.js "prompt" "./output.png"3. Report the saved file path
真正的魔法在脚本里。下面是一个完整实现,你可以直接放到 ~/.claude/scripts/generate-image.js:
#!/usr/bin/env nodeconst https = require('https');const fs = require('fs');const path = require('path');const API_KEY = process.env.GOOGLE_AI_API_KEY || 'your-api-key-here';// 注意:请查看 https://ai.google.dev/gemini-api/docs/imagen 获取最新模型 IDconst MODEL = 'imagen-4.0-generate-001';async function generateImage(prompt, outputPath) {const requestBody = {instances: [{ prompt }],parameters: {sampleCount: 1,aspectRatio: '16:9',personGeneration: 'dont_allow'}};const body = JSON.stringify(requestBody);const options = {hostname: 'generativelanguage.googleapis.com',port: 443,path: `/v1beta/models/${MODEL}:predict?key=${API_KEY}`,method: 'POST',headers: {'Content-Type': 'application/json','Content-Length': Buffer.byteLength(body)}};return new Promise((resolve, reject) => {const req = https.request(options, (res) => {let data = '';res.on('data', chunk => data += chunk);res.on('end', () => {const response = JSON.parse(data);if (response.error) {reject(new Error(response.error.message));return;}if (response.predictions?.[0]) {const imageData = response.predictions[0].bytesBase64Encoded;const dir = path.dirname(outputPath);if (dir && !fs.existsSync(dir)) {fs.mkdirSync(dir, { recursive: true });}fs.writeFileSync(outputPath, Buffer.from(imageData, 'base64'));resolve(outputPath);}});});req.on('error', reject);req.write(body);req.end();});}const [prompt, outputPath = `./generated-${Date.now()}.png`] = process.argv.slice(2);generateImage(prompt, outputPath).then(p => console.log(`Saved: ${p}`));
获取 API Key:
- 前往 Google AI Studio
- 创建新的 API key
- 设置
GOOGLE_AI_API_KEY环境变量,或直接粘贴到脚本中
使用示例:
/imagen "a minimalist logo for a coding blog, orange and white"/imagen "abstract geometric pattern" ./public/hero.png/imagen "futuristic terminal interface, dark theme, neon accents"
API 参数:
sampleCount— 生成图片数量(1-4,默认4)aspectRatio— 输出尺寸比例:1:1、3:4、4:3、9:16、16:9(默认1:1)personGeneration— 控制图片中是否包含人物:dont_allow— 完全禁止人物allow_adult— 仅允许成人(默认)allow_all— 允许成人和儿童
imageSize— 分辨率:1K或2K(仅 Standard/Ultra 模型支持)
可用模型:
imagen-4.0-generate-001— 标准版,最佳质量imagen-4.0-ultra-generate-001— Ultra 版,最高质量imagen-4.0-fast-generate-001— 快速版,更低延迟imagen-3.0-generate-001— 上一代
这个系列里的一些封面图和插图?就是用 /imagen 生成的。你看到的那些表情包?用 /meme 做的。
关键在于:只要有 API,你就能把它包装成一个命令。社交媒体发布、翻译、图片生成、数据查询——全都能变成斜杠命令。
命令设计原则
职责单一 — 一个命令做好一件事。/review 负责审查,/test 负责测试。别做瑞士军刀。
输出格式清晰 — 明确告诉 Claude 怎么呈现结果。用列表?分类?按严重程度?写清楚。
包含约束条件 — Claude 不应该做什么?"不改变行为"或"不修改测试"能防止越界操作。
选对模型 — 快速查找用 Haiku,常规任务用 Sonnet,复杂推理用 Opus。让模型匹配任务。
预授权安全工具 — 如果命令总是需要 git 或 npm,用 allowed-tools 跳过权限确认。
调试命令
如果命令不生效:
- 检查路径 — 是不是放在
.claude/commands/或~/.claude/commands/下? - 检查扩展名 — 必须是
.md - 运行
/help— 你的命令应该出现在列表中 - 检查 frontmatter — YAML 格式必须正确(缩进、特殊字符加引号)
下一篇预告
自定义命令把你的工作流编码为可复用的操作。但如果你想把命令分享给团队之外的人呢?如果你想让命令在不同项目中通用,而不用到处复制文件呢?
这就是 Skills(技能模块)的用武之地了。在第5篇:Skills中,我们会探索如何将命令打包成更广泛的分发形式,创建更强大的自动化。
创建命令
mkdir -p .claude/commands — 创建目录
.claude/commands/name.md — 基础命令
.claude/commands/git/commit.md — 命名空间(/git:commit)
Frontmatter 字段
description — 在 /help 中显示
argument-hint — 用法提示
allowed-tools — 如 Bash(git *), Read, Write
model — 指定模型
参数占位符
$ARGUMENTS — 命令后的所有内容
$1、$2、$3 — 位置参数
查看命令 — /help
Stay Updated
Get notified about new posts on automation, productivity tips, indie hacking, and web3.
No spam, ever. Unsubscribe anytime.

