
4 - Claude CLI Custom Commands: Build Your Personal AI Toolkit
Table of Contents
- Introduction
- What Are Custom Commands?
- Your First Custom Command
- Essential Command Library
- Advanced Command Features
- Organizing Your Command Arsenal
- Team Collaboration
- Real-World Examples
- FAQ
- Conclusion
Introduction
Picture this: You're typing the same Claude CLI prompt for the third time today. "Review this code for bugs, performance issues, security vulnerabilities..." and halfway through, you think, "there HAS to be a better way." ๐คฆโโ๏ธ
Spoiler alert: There is! And it's called custom slash commands.
Think of custom commands as your personal AI spellbook ๐โจ. Instead of reciting the entire incantation every time, you just say the magic word (/review), and BOOM โ Claude knows exactly what you want.
In this guide, you'll build your own command library that'll make you look like a terminal wizard ๐งโโ๏ธ. We're talking one-word commands for code reviews, test generation, documentation, and even Zimbra server management. By the end, you'll have your own AI toolkit that does the heavy lifting while you sip coffee โ.
Let's turn you into a Claude CLI power user!
What Are Custom Commands?
Custom commands are reusable prompt templates stored as markdown files. Instead of typing long prompts every time, you create a command once and invoke it forever.
The Magic Behind the Curtain ๐ฉ
When you type /review, Claude CLI:
- Looks in
.claude/commands/folder - Finds
review.md - Reads the prompt inside
- Executes it with your current context
It's basically prompt automation โ because who has time to be verbose when there's code to ship? ๐
Two Types of Commands
| Command Type | Location | Shared Via | Best For | Example |
|--------------|----------|------------|----------|---------|
| ๐ข Project | .claude/commands/ | Git commits | Team workflows | /deploy-staging |
| ๐ค Personal | ~/.claude/commands/ | Not shared | Individual preferences | /morning-standup |
Quick Memory Tip ๐ง : Project = shared with team via git. Personal = your secret toolkit.
Why You Need This (Besides Being Lazy)
Before Custom Commands:
> Perform a comprehensive code review checking for bugs, edge cases,
performance issues, security vulnerabilities, best practices violations,
code style consistency, error handling, and provide specific suggestions
with code examples for each issue found...
๐ด Everyone fell asleep before finishing
After Custom Commands:
> /review
โจ Chef's kiss
Real Benefits:
- โก Faster - Type
/reviewvs 200 characters - ๐ฏ Consistent - Same quality checks every time
- ๐ง Knowledge capture - Team expertise codified
- ๐ค Shareable - Onboard new devs instantly
- ๐ฐ Token savings - 20% reduction in some workflows
Your First Custom Command
Let's create your first command! We'll start with something immediately useful: code review.
Step 1: Create the Commands Directory
# For project-specific commands
mkdir -p .claude/commands
# For personal commands
mkdir -p ~/.claude/commands
# Let's start with a project command
cd .claude/commands
Step 2: Create Your First Command File
# Create review.md
touch review.md
The filename becomes your command. review.md โ /review ๐ช
Step 3: Write the Command Prompt
Open review.md and add:
---
description: Comprehensive code review
---
Review this code thoroughly and provide:
## ๐ Bugs & Edge Cases
Identify potential bugs, edge cases, and error conditions
## โก Performance Issues
Highlight performance bottlenecks and optimization opportunities
## ๐ Security Vulnerabilities
Check for common security issues (SQL injection, XSS, auth bypasses, etc.)
## โจ Best Practices
Suggest improvements following language/framework best practices
## ๐จ Code Style
Note any style inconsistencies or readability issues
For each issue:
- Explain the problem clearly
- Show the fix with code
- Explain why it matters
Be specific, actionable, and constructive.
Pro tip: That --- section at the top is frontmatter. The description shows up in /help.
Step 4: Test Your Command! ๐
# Start Claude CLI
claude
# Use your new command
> /review @src/auth.js
Watch in amazement as Claude performs your entire review checklist in one command! ๐ญ
Step 5: Feel Like a Productivity Ninja ๐ฅท
You just automated something you used to type manually. That's basically developer enlightenment.
The journey from repetitive task to custom command magic - it's easier than you think!
Essential Command Library
Here's a starter pack of must-have commands. Copy, customize, unleash! ๐ช
Your custom command library organized by category - from code quality to emergency fixes
Command Quick Reference
The Core 5 (Start Here ๐ฏ):
| Command | Purpose | Key Benefit | Emoji |
|---------|---------|-------------|-------|
| /review | Code review | Catch bugs before production | ๐ |
| /test | Generate tests | 100% coverage automatically | โ
|
| /docs | Write documentation | Docs that actually exist | ๐ |
| /fix | Debug issues | Faster problem resolution | ๐ ๏ธ |
| /commit | Commit messages | Semantic versioning ready | ๐ |
Memory Tip ๐ง : Think "Review โ Test โ Document โ Fix โ Commit" - the natural development workflow.
1. Code Review Command (review.md)
Already covered above, but this one's your bread and butter ๐๐ง.
2. Test Generator (test.md)
---
description: Generate comprehensive unit tests
---
Generate comprehensive unit tests for this code using the project's testing framework.
Include:
## โ
Happy Path Tests
Test the expected behavior with valid inputs
## ๐ซ Edge Cases
Test boundary conditions, empty inputs, null values
## ๐ฅ Error Handling
Test invalid inputs and error scenarios
## ๐ญ Mocks & Stubs
Create necessary mocks for external dependencies
## ๐ Test Coverage
Aim for 100% code coverage of the target functionality
Use descriptive test names following the pattern:
`it('should [expected behavior] when [condition]')`
Make tests readable, maintainable, and fast.
Usage:
> /test @src/utils/formatDate.js
Boom! Instant test suite. Your future self (debugging at 2 AM) will thank you. ๐
3. Documentation Writer (docs.md)
---
description: Generate comprehensive documentation
---
Create detailed documentation for this code:
## ๐ Overview
Brief description of what this code does and why it exists
## ๐ฏ Purpose & Use Cases
When and why you'd use this
## ๐ API Reference
### Functions/Methods
For each function:
- **Signature**: Full function signature with types
- **Parameters**: Describe each parameter
- **Returns**: What it returns
- **Throws**: Any exceptions/errors
## ๐ก Usage Examples
Provide 2-3 practical examples showing:
- Basic usage
- Common use case
- Advanced scenario
## โ ๏ธ Gotchas & Limitations
Edge cases, performance considerations, known limitations
## ๐ Related
Links to related functions, documentation, resources
Write for developers who've never seen this code before.
Make it scannable with good headers and examples.
Because documentation that writes itself is the only documentation that gets written. ๐
4. Bug Fixer (fix.md)
---
description: Debug and fix issues
---
Analyze this code for bugs and fix them:
## ๐ Investigation
1. Identify all potential bugs
2. Explain what causes each bug
3. Rate severity (Critical/High/Medium/Low)
## ๐ ๏ธ Fixes
For each bug:
Bug: [Description]
Problem: [Explain the issue] Fix: [Show the corrected code] Why: [Explain why this fix works]
## โ
Verification
Suggest how to verify the fix works
## ๐ซ Prevention
Recommend practices to prevent similar bugs
Be methodical, thorough, and educational.
Pro mode:
> /fix @src/api/auth.js --verbose
5. Commit Message Generator (commit.md)
---
description: Generate conventional commit message
---
Based on these code changes, generate a conventional commit message.
**Format:**
type(scope): subject
body (optional)
footer (optional)
**Types:**
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation only
- `style`: Code style (formatting, semicolons, etc.)
- `refactor`: Code change that neither fixes a bug nor adds a feature
- `perf`: Performance improvement
- `test`: Adding or updating tests
- `chore`: Maintenance (dependencies, build, etc.)
**Rules:**
- Subject: max 50 chars, imperative mood, no period
- Body: Explain *what* and *why* (not how)
- Footer: Reference issues/breaking changes
Output ONLY the commit message (no extra explanation).
Usage:
# Stage your changes
git add .
# Generate commit message
> /commit
# Copy and commit
git commit -m "[paste Claude's message]"
Or automate it completely:
git commit -m "$(echo '' | claude -p '/commit')"
Suddenly every commit message is semantic and professional. You're welcome. ๐
Advanced Command Features
Ready to level up? Let's get fancy! ๐ฉโจ
Command Feature Matrix
| Feature | What It Does | Use Case | Complexity |
|---------|-------------|----------|------------|
| ๐ Arguments | Pass values like $ARGUMENTS or $1 | Dynamic names/paths | โญโญ |
| ๐ Multi-file | Process directories | Batch refactoring | โญโญโญ |
| ๐ Conditional | Adapt to file type | Smart reviews | โญโญโญโญ |
| ๐ Chaining | Reference other commands | Complex workflows | โญโญโญโญโญ |
Using Arguments in Commands
Commands can accept file paths and arguments using two patterns:
| Variable | What It Does | Example | When to Use |
|----------|-------------|---------|-------------|
| $ARGUMENTS | All arguments together | $ARGUMENTS = "UserProfile dark" | Simple commands with one input |
| $1, $2, $3 | Individual arguments | $1 = "UserProfile", $2 = "dark" | Structured commands with multiple parameters |
create-component.md:
---
description: Create React component with tests
argument-hint: <ComponentName>
---
Create a new React component called `$1` with:
1. Component file (src/components/$1.jsx)
2. Styles file (src/components/$1.module.css)
3. Test file (src/components/$1.test.jsx)
4. Storybook story (src/components/$1.stories.jsx)
The component should:
- Use TypeScript
- Be fully accessible (ARIA labels, keyboard navigation)
- Have PropTypes/TypeScript types
- Include JSDoc comments
- Follow our style guide
Create all files and show the complete code.
Usage:
> /create-component UserProfile
Claude generates 4 files for you. That's not automation, that's wizardry! ๐งโโ๏ธโจ
Multi-File Commands
Want to process multiple files? Easy!
refactor-directory.md:
---
description: Refactor entire directory
---
Analyze all files in this directory and refactor to:
1. **Consistency**: Unified code style
2. **DRY**: Extract repeated code
3. **Performance**: Optimize where possible
4. **Types**: Add/improve TypeScript types
5. **Tests**: Ensure all functions are tested
Process each file systematically.
Show what changed and why.
Usage:
> /refactor-directory @src/utils/
Conditional Logic in Commands
smart-review.md:
---
description: Context-aware code review
---
Review this code with focus areas based on file type:
**If JavaScript/TypeScript:**
- Async/await usage
- Error handling
- Type safety
- Bundle size impact
**If Python:**
- PEP 8 compliance
- Type hints
- Exception handling
- Virtual environment compatibility
**If Bash:**
- Error handling (`set -e`)
- Input validation
- Portability (#!/bin/bash vs #!/bin/sh)
- Security (command injection)
**If CSS:**
- Browser compatibility
- Performance (avoid expensive selectors)
- Accessibility (color contrast, focus states)
- Maintainability
**If SQL:**
- Injection vulnerabilities
- Index usage
- Query performance
- Transaction handling
Adapt the review to the language context.
Smart commands that adapt? Now we're cooking! ๐จโ๐ณ
๐ฏ Quick Challenge: Before reading the next section, can you recall the 5 core commands? (Hint: development workflow order)
<details> <summary>Click to reveal answer</summary>/review- Code review ๐/test- Generate tests โ/docs- Write documentation ๐/fix- Debug issues ๐ ๏ธ/commit- Commit messages ๐
Organizing Your Command Arsenal
As your command library grows, organization becomes key. Here's how the pros do it:
Directory Structure Patterns
.claude/commands/
โโโ code/
โ โโโ review.md
โ โโโ refactor.md
โ โโโ optimize.md
โโโ testing/
โ โโโ test.md
โ โโโ e2e.md
โ โโโ coverage.md
โโโ docs/
โ โโโ api.md
โ โโโ readme.md
โ โโโ changelog.md
โโโ git/
โ โโโ commit.md
โ โโโ pr-description.md
โ โโโ release-notes.md
โโโ zimbra/
โโโ audit.md
โโโ provision.md
โโโ monitor.md
Namespaced commands:
/code/review/testing/e2e/zimbra/audit
Organization Strategy
| Team Size | Command Count | Structure | Why | |-----------|--------------|-----------|-----| | 1-3 devs | 1-10 | Flat | Simple, fast access | | 4-10 devs | 11-30 | Categories (5-7) | Clear grouping | | 11+ devs | 31+ | Categories + subfolders | Scalable organization |
Naming Conventions
Good names:
/reviewโ Clear and simple/testโ One word, obvious meaning/fix-authโ Specific but understandable
Bad names:
/do-the-thingโ What thing? ๐คทโโ๏ธ/xโ Too cryptic/please-review-my-code-and-tell-me-if-its-goodโ Just... no
Pro tip: Keep command names short but descriptive. You'll be typing them a lot!
Command Versioning
Track your commands in git:
# .gitignore
# DON'T ignore .claude/!
# โ .claude/
# DO commit your commands
git add .claude/commands/
git commit -m "feat: add custom review command"
Now your team gets your awesome commands automatically! ๐
Team Collaboration
Custom commands shine brightest when shared. Here's how to make them team superpowers:
Onboarding New Developers
welcome.md:
---
description: Onboard new team member
---
Welcome to the team! Let me help you get started. ๐
I'll guide you through:
1. **Project Setup**
- Clone dependencies
- Environment variables
- Database setup
- Running locally
2. **Our Workflows**
- Git branching strategy
- PR process
- Code review standards
- Testing requirements
3. **Useful Commands**
- `/review` - Code review
- `/test` - Generate tests
- `/commit` - Commit messages
- `/docs` - Documentation
4. **Where Things Live**
- API routes: /src/api/
- Components: /src/components/
- Utils: /src/utils/
- Tests: /__tests__/
Ask me anything about the codebase! I'm here to help. ๐
Usage:
> /welcome
New dev goes from zero to productive in record time. That's leadership! ๐ผ
Team Code Review Standards
team-review.md:
---
description: Team code review checklist
---
Perform code review following our team standards:
## โ
Code Quality
- [ ] Follows our style guide (check .prettierrc)
- [ ] No console.logs or debug code
- [ ] Proper error handling
- [ ] Meaningful variable names
## ๐งช Testing
- [ ] New code has unit tests
- [ ] Tests follow AAA pattern (Arrange, Act, Assert)
- [ ] Edge cases are covered
- [ ] Tests are deterministic (no flaky tests)
## ๐ Security
- [ ] No hardcoded secrets/API keys
- [ ] Input validation on user data
- [ ] SQL queries use parameterized statements
- [ ] Authentication/authorization checks present
## ๐ Documentation
- [ ] Public functions have JSDoc comments
- [ ] README updated if needed
- [ ] API changes documented
## โก Performance
- [ ] No N+1 queries
- [ ] Large lists are paginated
- [ ] Heavy operations are async
- [ ] Proper indexes on database queries
Provide feedback in this format:
**Must Fix:** Critical issues blocking merge
**Should Fix:** Important but not blocking
**Nice to Have:** Suggestions for improvement
**Praise:** What was done well! ๐
Be specific, kind, and constructive.
Consistency across reviews? Check. โ
Shared Zimbra Admin Commands
For teams managing Zimbra servers, create a shared toolkit:
zimbra/audit.md:
---
description: Audit Zimbra accounts
---
Analyze these Zimbra account details and generate an audit report:
## ๐ Account Statistics
- Total active accounts
- Inactive accounts (>90 days)
- Locked/disabled accounts
- Quota utilization
## โ ๏ธ Issues Found
- Accounts over 90% quota
- Accounts with no recent login
- Accounts with suspicious activity
- Configuration inconsistencies
## ๐ก Recommendations
- Accounts to archive/delete
- Quota adjustments needed
- Security policy updates
- Performance optimizations
## ๐ Trends
- Growth rate
- Resource usage patterns
- Common issues
Format as professional report for management.
zimbra/quick-fix.md:
---
description: Common Zimbra fixes
---
Diagnose this Zimbra issue and provide fix:
## ๐ Common Issues Checklist
**Email Delivery:**
- Check SMTP logs
- Verify DNS (MX, SPF, DKIM)
- Check postfix queue
- Review sender reputation
**Authentication:**
- LDAP connectivity
- Password policy
- Account status
- SSL certificate validity
**Performance:**
- Memory usage
- Disk space
- Database size
- Queue length
**Web Interface:**
- Jetty service status
- Browser cache
- Proxy configuration
- SSL/TLS settings
For each issue found:
1. Root cause
2. Immediate fix
3. Prevention strategy
4. Monitoring recommendation
Provide ZCS commands to execute.
Now your whole team speaks Zimbra fluently! ๐ง
Real-World Examples
Let's see these commands in action with realistic scenarios:
Scenario 1: Squashing a Pesky Bug ๐
The Problem: Your auth middleware is letting unauthenticated requests through. Not good!
The Solution:
> /fix @src/middleware/auth.js
Claude's Response:
## ๐ Investigation
Found 2 critical bugs:
### Bug 1: Missing await on token verification
**Severity:** Critical
**Problem:** Token verification is async but not awaited, so execution continues before validation completes.
**Current Code:**
```javascript
const user = jwt.verify(token, SECRET);
next();
Fixed Code:
try {
const user = await jwt.verify(token, SECRET);
req.user = user;
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
Why: Without await, the middleware doesn't wait for verification. This lets unverified requests through!
[... more bugs and fixes ...]
Bug: crushed. Security: restored. Coffee: earned. โ
### Scenario 2: Writing the Perfect PR
**The Workflow:**
```bash
# Make your changes
git add .
# Generate commit message
> /commit
# Copy output: "feat(auth): add JWT refresh token support"
git commit -m "feat(auth): add JWT refresh token support"
# Generate PR description
> /pr-description
pr-description.md:
---
description: Generate PR description
---
Based on the commits in this branch, create a comprehensive PR description:
## ๐ Summary
Brief overview of what changed
## ๐ฏ Changes Made
- Bullet list of key changes
- Focus on *what* and *why*
## ๐งช Testing
How to test these changes:
- Step-by-step test instructions
- Test scenarios covered
## ๐ธ Screenshots/Examples
(If applicable) Describe visual changes or output examples
## โ ๏ธ Breaking Changes
(If applicable) What breaks and migration steps
## ๐ Related
- Related PRs/issues
- Documentation links
## โ
Checklist
- [ ] Tests added/updated
- [ ] Documentation updated
- [ ] No breaking changes (or documented)
- [ ] Ready for review
Keep it clear, informative, and helpful for reviewers.
Claude's Output:
## ๐ Summary
Implements JWT refresh token support to improve security and user experience by allowing long-lived sessions without compromising security.
## ๐ฏ Changes Made
- Added refresh token generation and validation
- Implemented `/api/auth/refresh` endpoint
- Updated middleware to handle token expiration
- Added refresh token storage in httpOnly cookie
- Created token rotation mechanism
## ๐งช Testing
1. Log in with valid credentials
2. Observe access token (5min) and refresh token (7days) in cookies
3. Wait for access token expiration
4. Call protected endpoint - should auto-refresh
5. Verify new access token issued
## โ ๏ธ Breaking Changes
None - fully backward compatible
## โ
Checklist
- [x] Tests added/updated
- [x] Documentation updated
- [x] No breaking changes
- [x] Ready for review
Copy, paste, create PR. Your team thinks you're a documentation wizard! ๐โจ
Scenario 3: Zimbra Firefighting ๐
3 AM. Your phone rings. Email's down.
> /zimbra/emergency
emergency.md:
---
description: Emergency Zimbra diagnostics
---
Run emergency diagnostics:
## ๐จ Critical Checks
**Services:**
```bash
su - zimbra -c "zmcontrol status"
Queue:
su - zimbra -c "postqueue -p | tail"
Disk Space:
df -h | grep zimbra
Recent Errors:
tail -100 /opt/zimbra/log/mailbox.log | grep -i error
๐ Analysis
Based on the output above:
- Identify the root cause
- Assess severity and impact
- Provide immediate fix
- Suggest monitoring to prevent recurrence
๐ ๏ธ Quick Fixes
Provide copy-paste commands to resolve
๐ Status Report
Brief status for management/stakeholders
Keep it fast - production is down!
From panic to resolution in minutes. You're the hero Zimbra deserves! ๐ฆธโโ๏ธ
---
## FAQ
### Where are custom commands stored?
**Project commands:** `.claude/commands/` (committed to git)
**Personal commands:** `~/.claude/commands/` (your machine only)
Think of it like git hooks - project stuff in the repo, personal preferences in home directory.
### Can commands call other commands?
Not directly, but you can reference them in prompts:
```markdown
First, run /review on this code.
Then, generate tests with /test.
Finally, create documentation with /docs.
It's like a command macro! ๐ฎ
How do I share commands with my team?
# Commit to git
git add .claude/commands/
git commit -m "feat: add team commands"
git push
# Team pulls
git pull
# Commands automatically available!
> /help
# Shows new commands
Git makes sharing magical. โจ
Can I use environment variables in commands?
Yes! Though you'll need to reference them in your prompt:
Deploy to ${ENVIRONMENT} using configuration from ${CONFIG_PATH}
Or use MCP servers for dynamic data (covered in future posts!).
Do commands work in print mode?
Absolutely!
claude -p "/review" < src/auth.js
Automate ALL the things! ๐ค
How do I debug a command that's not working?
- Check the markdown syntax:
cat .claude/commands/review.md
- Verify frontmatter format:
---
description: Your description
---
- Check file permissions:
ls -la .claude/commands/
- Test manually:
> cat .claude/commands/review.md
# Copy the content
> [paste and test]
Can I have command aliases?
Create multiple files with the same content:
# Both do the same thing
cp .claude/commands/review.md .claude/commands/cr.md
Now /review and /cr both work. Efficiency! โก
Conclusion
Holy smokes, you did it! ๐ You just went from typing long prompts like it's 1995 to wielding custom commands like a terminal ninja!
Let's recap your new superpowers:
- โ Created custom slash commands
- โ Built an essential command library
- โ Learned advanced techniques (arguments, multi-file, conditional)
- โ Organized commands professionally
- โ Set up team collaboration
- โ Saw real-world examples in action
Your command arsenal now includes:
/review- Never miss a bug again/test- Tests that write themselves/docs- Documentation that actually exists/commit- Semantic messages automatically/fix- Debug like a boss- Custom Zimbra commands - Email admin on easy mode
What's Next?
In the next post, "Claude CLI in VS Code: The Complete IDE Integration Guide", we'll level up AGAIN by:
- Installing the VS Code extension
- Integrating commands into your IDE
- Setting up keyboard shortcuts
- Creating custom tasks
- Building the ultimate dev environment
Custom commands in your IDE? That's not productivity โ that's superpowers! ๐ฆธโโ๏ธ
Your Challenge ๐ฏ
Before the next post, create 3 custom commands:
- One for your most common task
- One that makes your team laugh (yes, fun commands are allowed!)
- One for something you've always wanted to automate
Share your coolest commands in the comments! Let's build the ultimate community command library together. ๐ช
Pro Tips to Remember
- Start small - One command at a time
- Iterate - Improve commands as you use them
- Share generously - Your commands help others
- Have fun - Make commands that spark joy โจ
- Version control - Always commit .claude/
You're not just using Claude CLI anymore. You're mastering it.
Now go forth and command! ๐
Resources
- Previous Post: Automation & Scripting Guide
- Custom Commands Documentation
- Claude-Command-Suite - Community commands
- Awesome Claude Code - Curated list
Next in Series: Claude CLI in VS Code: The Complete IDE Integration Guide โ
Built something cool? Share your commands! Drop them in the comments or tweet them with #ClaudeCLI
Have questions? Ask below โ I read and respond to every comment! ๐ฌ
Loved this guide? Share it with your team and help them discover their inner CLI wizard! ๐งโโ๏ธ
Last Updated: November 2025 | Claude Code Version 2.x | Part 4 of 8 in the Claude CLI Zero to Hero Series
P.S. - If you create a command called /make-it-work, you're legally required to share it. Those are the rules. ๐