You know that feeling when you’ve found the perfect workflow hack? Yeah, that’s what slash commands are for Claude Code. They’re the shortcuts that turn tedious multi-step processes into one-line magic. Whether you’re using the built-ins or crafting custom ones for your team, slash commands are absolute game-changers.
Let’s dive into what you can do with them.
Why Slash Commands Matter
Think of slash commands as your personal assistant inside Claude Code. Instead of manually typing out a series of operations, you hit / and suddenly you’ve got access to powerful shortcuts. They speed up your work, reduce errors, and—here’s the kicker—you can share them with your entire team through version control.
The built-in commands handle the everyday tasks: getting help, clearing your session, reviewing code, and planning work. But the real power? That’s where custom commands come in. You can tailor them to your exact workflow.
The Productivity Multiplier
Let’s do the math. If you save 2 minutes per command and you use 10 commands daily, that’s 20 minutes a day. Over a year with 250 work days, that’s 83 hours—roughly two work weeks of reclaimed time. But here’s the thing: slash commands often save 5-10 minutes, not 2. And the efficiency gains compound when you share them across a team.
Consider a typical deployment process. Without a command, you’re running 15 separate steps: checking tests, bumping versions, generating changelogs, tagging Git, building artifacts, uploading to registries, notifying teams. Each step takes 2-3 minutes and introduces the possibility of error. A single /release major command does all of this automatically, consistently, and correctly every single time. That’s not 2 minutes saved—that’s 20 minutes saved with zero error introduction. Across your team of 10 developers doing releases weekly, that’s 200 minutes saved per week.
Custom commands are also mistake-reducers. When you script a deployment process into /deploy production, you eliminate the chance of running it wrong. No more typos in environment variables, no more accidental force pushes, no more “oops I deleted the wrong branch.” The command becomes your source of truth for how operations are supposed to happen.
Consistency Across Teams
Imagine this: Your team has a standard way to create features, run tests, deploy code, and generate documentation. But it’s scattered across five different Slack messages, a wiki page nobody updates, and tribal knowledge. Now imagine /feature, /test, /deploy, and /docs all just work the same way for everyone.
That’s what custom commands deliver. They’re version-controlled, discoverable through /help, and shared automatically through Git. Every time someone pulls changes, they get the latest command definitions. No more outdated instructions. No more “wait, how did we do this again?” Or worse, developers creating their own shortcuts that conflict with team standards.
This consistency matters more than you might think. When onboarding a new developer, instead of spending an hour explaining your deployment process, your testing workflow, and your branching strategy, you say “run /onboard-dev and /help to see what we have.” They’re productive in 30 minutes instead of 3 days.
Built-in Slash Commands
Let’s walk through the commands that come straight out of the box with Claude Code.
/help – Your Command Reference
The /help command is your safety net. Use it to list all available commands in your current context.
/help
This shows you:
- All built-in commands with descriptions
- Custom commands in
.claude/commands/ - Command parameters and usage examples
- Quick keyboard shortcuts
- Filtering options to find specific commands
Run this when you’re unsure what’s available or need a syntax reminder. It’s always there. Pro tip: You can search within help: /help deploy shows only commands related to deployment. This is incredibly useful in large projects with dozens of custom commands—instead of scrolling through everything, you get just the relevant commands.
/clear – Reset Your Session
Sometimes you need a fresh start. The /clear command wipes your current session context without losing your files.
/clear
This is useful when:
- You’ve been working on something for hours and context is jumbled
- You want to pivot to a completely different task
- Memory feels cluttered and you want pristine focus
- You’ve been exploring multiple ideas and want to start fresh on the chosen direction
Note: This doesn’t delete your actual work, just the conversational context. Your files are safe. Your Git history is intact. Only the in-memory conversation state gets reset. This is particularly useful when you’ve been brainstorming multiple architectural approaches and want to commit to one, starting fresh without the mental baggage of rejected ideas.
Real-world example: You spent 2 hours exploring three different API designs. You settled on Option C. Your context window is full of discussion about Options A and B. Run /clear, then explain Option C fresh. Claude Code now has maximum context available for Option C without the noise of rejected alternatives.
/compact – Compress Context Automatically
The /compact command intelligently summarizes your session history, keeping the most relevant information while trimming the fat.
/compact
This is Claude Code’s way of saying “Hey, you’ve got a lot going on. Let me organize this.” It’s especially useful in long sessions where you’ve tackled multiple topics and context is getting heavy. Instead of hitting the token limit and losing the whole conversation, /compact distills it down.
The command analyzes your conversation and creates a summary that preserves:
- Key decisions you made
- Code changes you approved
- Important context about your architecture
- Unresolved questions or known issues
Then it removes verbose explanations, tangential discussions, and redundant confirmations. You go from a 150,000-token conversation to a 50,000-token summary that captures everything that matters.
/init – Initialize a New Project
Starting fresh? The /init command scaffolds a new project structure for you.
/init my-awesome-project
This creates:
- Project directories following your configured template
- Basic configuration files (.gitignore, package.json, tsconfig, etc.)
- README with project structure
- Git initialization (if configured)
- Directory structure aligned with best practices
Perfect for getting up and running without manually setting up folders. Instead of spending 30 minutes creating directories, adding boilerplate files, and configuring tools, you run one command and you’re ready to start coding. The time savings compound. Across a team doing multiple projects per quarter, this saves hundreds of hours per year.
/review – Trigger Code Review Mode
The /review command activates Claude Code’s review subagent to analyze your code.
/review
Or review a specific file:
/review src/utils.ts
This analyzes:
- Code structure and patterns (is it well-organized?)
- Potential bugs and edge cases (what could break?)
- Performance considerations (are there bottlenecks?)
- Best practices alignment (does it follow conventions?)
- Documentation gaps (is it self-explanatory?)
It’s like having a senior engineer glance at your code. Useful before you commit. The review provides specific line numbers, explains the issue, and suggests fixes. You can accept, reject, or modify suggestions. Many developers use this as a pre-commit hook—review with Claude before pushing to a PR, then the human reviewer focuses on architectural concerns rather than catching bugs.
Pro workflow: Commit all your changes locally. Run /review on modified files. Accept/modify suggestions. Run tests. Then push to your branch and create a PR. Your PR reviewers see cleaner, more reviewed code and can focus on design critique rather than syntax issues.
/plan – Generate Execution Plans
When you’re facing a complex task, /plan breaks it down into manageable steps.
/plan build a REST API with auth and logging
This creates:
- Phased execution steps (Phase 1: Setup, Phase 2: Core endpoints, Phase 3: Auth, Phase 4: Logging, Phase 5: Testing)
- Dependencies between tasks (which things must happen first?)
- Effort estimates (2 hours, 30 minutes, etc.)
- Risk assessment (what could go wrong?)
- Success criteria (how do we know we’re done?)
Invaluable for planning before diving into implementation. The plan gives you a roadmap, helps you estimate timeline, and identifies risks upfront. You can reference this plan throughout development: “We’re in Phase 3, working on JWT validation.” vs “I’m not sure what I’m supposed to be building.”
/test – Run Test Suite
The /test command executes your configured test suite and reports results.
/test
Or target specific tests:
/test auth-module
/test --coverage
/test --watch
Results include:
- Pass/fail counts (12 passed, 2 failed out of 14 total)
- Coverage metrics (87% statement coverage, 92% branch coverage)
- Failed test details (exactly which assertions failed and why)
- Performance metrics (slowest tests)
- Suggestions for improving coverage
Run tests before committing, before pushing, before deploying. Make testing a habit. Tests aren’t just validation—they’re documentation of how your code is supposed to work. When you come back to code in 6 months, tests show you the intended behavior.
/optimize – Performance Analysis
The /optimize command scans your code for performance improvements.
/optimize src/
/optimize src/database.ts
Identifies:
- Inefficient algorithms (O(n²) where O(n log n) would work)
- Memory leaks or misuse (listeners not cleaned up, unreleased objects)
- Blocking operations (synchronous I/O where async would be better)
- Dependency chain bloat (importing more than necessary)
- Resource bottlenecks (database queries in loops, N+1 problems)
Run this before performance becomes an issue. Catching an O(n²) algorithm in development is infinitely better than discovering it in production handling 10,000 users. The command provides specific recommendations: “This loop runs 1000 times and queries the database on each iteration. Consider fetching all data once and filtering in memory.”
/git-status – Repository Overview
Quick view of your Git status without leaving Claude Code:
/git-status
Shows:
- Current branch (feature/user-auth)
- Staged/unstaged changes (3 files staged, 2 modified but not staged)
- Untracked files (new files not yet added)
- Commits ahead/behind your upstream (2 commits ahead of main)
- Dirty status (uncommitted changes exist)
This is your at-a-glance view. You can see your branch status without context-switching to a terminal.
/commit – Guided Git Commits
The /commit command helps you write semantic commits with proper formatting.
/commit
Prompts you for:
- Commit type (feat, fix, docs, refactor, test, style, chore)
- Scope (optional – which module? auth, database, api, etc.)
- Description (what changed and why)
- Breaking changes (did you change the API?)
- Referenced issues (closes #123, relates to #456)
Ensures your commit history stays clean and searchable. Six months later, you can do git log --grep="auth" and find all commits related to authentication. You can do git log --oneline | grep "^feat" to see all features. This matters more than you think—commit messages are how future you (and your team) understands what happened and why.
Real impact: Semantic commits enable automatic changelog generation. A feat: commit automatically appears in the “New Features” section. A fix: appears in “Bug Fixes.” A docs: appears in “Documentation.” Instead of manually writing release notes, your commits write them for you.
/docs – Generate Documentation
Extract and generate documentation from your codebase:
/docs src/ --format markdown
/docs api.ts --format openapi
Creates:
- API documentation (endpoints, parameters, responses)
- Function signatures (what does this function take and return?)
- Parameter descriptions (what does each parameter do?)
- Usage examples (how do you actually use this?)
- Type information (TypeScript types, return types)
Documentation stays in sync with code because it’s generated from the code. No more outdated docs that say one thing while code does another.
/improve-loop – Iterative Code Improvement
The /improve-loop command triggers Claude Code’s continuous improvement cycle:
/improve-loop my-module.js
/improve-loop src/ --target-score 4.5
This automated process:
- Analyzes code quality and identifies issues
- Runs tests to find failures or coverage gaps
- Refactors for readability and efficiency
- Documents changes and rationale
- Re-scores quality metrics
- Iterates until target quality threshold is met
It’s like having a senior engineer spend 30 minutes refactoring your code while you grab coffee. The command doesn’t just change code—it explains why. You learn patterns and best practices by seeing them applied to your codebase.
/dispatch – Run Specialized Agents
Need a specific agent for a complex task? The /dispatch command sends work to specialized subagents:
/dispatch prose-generator "write opening scene for cyberpunk novel"
/dispatch security-analyst "audit this authentication module"
/dispatch performance-tuner "optimize query on user database"
Available dispatch targets include:
- prose-generator: Long-form writing and content generation
- code-architect: System design and architecture decisions
- security-analyst: Security audits and vulnerability scanning
- performance-tuner: Optimization and profiling analysis
- test-engineer: Test suite generation and coverage analysis
- documentation-writer: Comprehensive documentation generation
This is how you bring in specialists without hiring them. Running /dispatch security-analyst on a production authentication module gets you a security audit that would cost thousands to hire a consultant for.
Understanding Command Syntax and Usage
Before diving deeper, let’s clarify how to actually use these commands effectively.
Basic Command Syntax
All slash commands follow a consistent pattern:
/command [required-arg] [optional-arg] [--flags]
Here’s how to read command documentation:
- Required arguments appear in angle brackets:
<filename> - Optional arguments appear in square brackets:
[--verbose] - Flags start with dashes and modify behavior:
--force,-f
Examples:
/test auth-module --coverage --watch
/deploy staging --skip-tests --notify
/optimize src/ --aggressive --report
Command Output and Results
Most slash commands produce structured output showing:
- What was executed: The actual steps taken
- Results: Success confirmations with specifics
- Time taken: How long the command took
- Next steps: Suggested follow-up commands
For example, /review might output:
✓ Code Review Complete (2.3s)
Structure: 4.2/5
- Well-organized module structure
- Minor: Consider extracting helper functions
Bugs: 1 found
- Line 42: Potential null reference in reducer function
Fix: Add null coalescing operator (??)
Performance: 3.8/5
- Acceptable for current scale
- Consider pagination for > 1000 items
Suggested Next: /commit to finalize changes
This gives you everything you need to know at a glance.
Custom Commands: Your Superpowers
Here’s where things get really fun. You can create custom commands tailored to your specific workflow. All custom commands live in .claude/commands/ directory.
Command File Format
Custom commands are Markdown files with an optional YAML frontmatter block. Here’s the structure:
---
name: my-command
description: What this command does
usage: /my-command [argument]
params:
- name: argument
description: What this argument does
required: true
aliases: [mc]
---
# What Your Command Does
Your command logic goes here. You can use:
- **$ARGUMENTS** - to reference passed arguments
- **$CWD** - current working directory
- **$PROJECT** - project root
- **$USER** - current user
Instructions and execution steps follow this section.
Let’s break this down:
Frontmatter Block (optional but recommended):
name: Command identifier (used after the/)description: One-line explanationusage: How to call it with syntaxparams: Array of parameters with descriptionsaliases: Alternate names for the command
Body: The actual instructions and logic for what the command executes.
Why Custom Commands Work Better Than Scripts
You might be thinking, “Can’t I just use bash scripts for this?” Sure, but custom commands have advantages:
Custom Command Advantages:
- Integrated discovery through
/help - Automatic parameter validation
- Team sharing through version control
- Built-in approval workflows for risky actions
- Semantic versioning and changelog tracking
- IDE integration and autocompletion
- Cross-platform compatibility (Windows, Mac, Linux)
- Built-in logging and audit trails
When you have 15 bash scripts scattered across your project, it’s hard to remember what they do or if they’re up-to-date. When you have /help listing 15 documented commands with clear descriptions, everyone on the team knows what’s available and how to use them. Bash scripts live in various places. Custom commands all live in .claude/commands/ and are discoverable through /help.
Creating Your First Custom Command
Let’s create a practical example. Here’s a command that initializes a new feature branch with proper naming:
---
name: feature
description: Create a new feature branch with standardized naming
usage: /feature <feature-name>
params:
- name: feature-name
description: Kebab-cased feature name
required: true
aliases: [f, feat]
---
# Create a Feature Branch
This command creates a new Git branch following the pattern `feature/feature-name`.
## Steps
1. Validate that `$ARGUMENTS` is provided and properly formatted
2. Check that the branch doesn't already exist
3. Create and checkout the new branch: `git checkout -b feature/$ARGUMENTS`
4. Create associated directories if needed: `src/$ARGUMENTS/`
5. Create a feature checklist file: `.claude/features/$ARGUMENTS.md`
6. Commit initial structure
## Automation
When you run `/feature user-authentication`, Claude Code will:
- Create `feature/user-authentication` branch
- Set up project structure
- Initialize a feature tracking file
- Switch to the new branch
Save this as .claude/commands/feature.md and you’ve got yourself a custom command.
Parameterized Commands with $ARGUMENTS
The $ARGUMENTS variable is how you pass information to your commands. It contains everything after the slash command name.
/deploy staging --force --notify
In your command file, $ARGUMENTS would be staging --force --notify. You can parse this however makes sense for your workflow.
Here’s an example that uses multiple arguments:
---
name: deploy
description: Deploy to specified environment
usage: /deploy <environment> [options]
---
# Deploy Application
This command deploys your application to the specified environment.
## Supported Environments
- **development**: Local development deployment
- **staging**: Staging environment for testing
- **production**: Production environment (requires approval)
## Execution
Parse the environment from `$ARGUMENTS`. If deploying to production:
1. Verify all tests pass
2. Confirm deployment with user
3. Create pre-deployment backup
4. Execute deployment script
5. Verify health checks
6. Notify team
Cookbook: 10 Ready-to-Use Custom Commands
Here are battle-tested commands you can copy into your .claude/commands/ directory right now:
1. Quick Code Review
---
name: review-quick
description: Fast 2-minute code review of specified file
usage: /review-quick <filepath>
aliases: [rq]
---
# Quick Code Review
Review the specified file for:
- Obvious bugs
- Security issues
- Style inconsistencies
- Documentation gaps
Parse `$ARGUMENTS` as the file path. Provide 5-7 key findings with fixes.
2. Generate Git Changelog
---
name: changelog
description: Generate changelog for commits since last tag
usage: /changelog [tag]
aliases: [cl]
---
# Generate Changelog
Creates a formatted changelog from Git commits.
If `$ARGUMENTS` is provided, use it as the tag reference. Otherwise, use the latest tag.
Format output as:
- ## Features
- ## Bug Fixes
- ## Breaking Changes
- ## Documentation
Include commit hashes and authors.
3. Setup Local Environment
---
name: setup-local
description: Complete local development environment setup
usage: /setup-local
---
# Setup Local Environment
Automate the tedious setup steps:
1. Verify Node version >= 18
2. Install dependencies: npm install
3. Copy .env.example to .env
4. Run database migrations
5. Seed sample data
6. Start dev server
7. Display startup checklist
Output a summary of what was configured.
4. Create Branch and PR
---
name: feature-pr
description: Create feature branch and GitHub PR template
usage: /feature-pr <feature-name>
aliases: [fpr]
---
# Feature Branch with PR
Streamline branch and PR creation:
1. Parse feature name from `$ARGUMENTS`
2. Create branch: git checkout -b feature/$ARGUMENTS
3. Create PR template in `.github/PULL_REQUEST_TEMPLATE.md`
4. Populate template with feature description prompts
5. Provide instructions for pushing branch
Use this workflow: Create feature → Make changes → PR template ready to go.
5. Run Security Audit
---
name: audit-security
description: Run comprehensive security checks
usage: /audit-security [--fix]
aliases: [sec, audit]
---
# Security Audit
Run security tools and generate report:
1. npm audit (JavaScript dependencies)
2. OWASP dependency check
3. Secret scanning (detect exposed credentials)
4. Security headers validation
5. SSL/TLS configuration check
If `--fix` in `$ARGUMENTS`, attempt automatic fixes.
Output risk levels and remediation steps.
6. Database Migration Generator
---
name: db-migrate
description: Generate database migration file
usage: /db-migrate <migration-name>
---
# Database Migration
Create timestamped migration file:
1. Parse migration name from `$ARGUMENTS`
2. Create file: migrations/[timestamp]\_$ARGUMENTS.sql
3. Add boilerplate with up/down methods
4. Provide migration template for common patterns
Output file path and instructions.
7. Performance Profile
---
name: profile
description: Run performance profiling on code
usage: /profile <file-or-function>
aliases: [perf]
---
# Performance Profile
Identify bottlenecks:
1. Parse target from `$ARGUMENTS`
2. Run Node.js profiler or equivalent
3. Generate flame graph or report
4. Highlight slow functions
5. Suggest optimizations
Output top 10 time sinks with recommendations.
8. Generate API Documentation
---
name: api-docs
description: Generate API documentation from code
usage: /api-docs [--format]
aliases: [docs]
---
# API Documentation
Extract and format API docs:
1. Scan routes/endpoints
2. Extract JSDoc comments
3. Parse parameters and return types
4. Include example requests/responses
5. Generate in Markdown, OpenAPI, or HTML
Check for `--format` in `$ARGUMENTS`. Default to Markdown.
9. Code Cleanup
---
name: cleanup
description: Auto-fix formatting, linting, and imports
usage: /cleanup [path]
---
# Code Cleanup
Run formatting and linting fixes:
1. Prettier formatting
2. ESLint auto-fix
3. Remove unused imports
4. Sort imports
5. Fix whitespace
Parse optional path from `$ARGUMENTS`. Default to entire src/.
Report files changed and issues fixed.
10. Team Knowledge Share
---
name: knowledge-share
description: Document learning and share with team
usage: /knowledge-share <topic>
---
# Knowledge Share
Create documentation for team learning:
1. Parse topic from `$ARGUMENTS`
2. Create file: knowledge/topic.md
3. Prompt for: Problem → Solution → Lessons Learned → Links
4. Add to version control
5. Generate team notification
Encourage continuous learning and knowledge distribution.
Real-World Command Patterns
Let’s look at some patterns that work brilliantly in production environments.
The Daily Standup Command
---
name: standup
description: Generate daily standup summary from recent commits
usage: /standup
---
# Daily Standup Summary
Generates what you accomplished today for team standups.
Extract from:
1. Commits in last 24 hours
2. Active branches
3. Incomplete TODOs in code
4. Test coverage changes
Format as:
- What I did
- What I'm doing next
- Blockers
This saves 5 minutes of "wait, what did I actually do yesterday?" confusion.
Run this before your daily standup. Instead of scrambling to remember what you did, you’ve got talking points ready. This single command can save your team 30 minutes per day (5 people × 6 minutes of confusion). Multiply that across a year and you’re looking at 125 hours of reclaimed time. That’s three work weeks just from having a standup command.
The Onboarding Command
---
name: onboard-dev
description: Get a new developer up and running
usage: /onboard-dev <dev-name>
---
# Developer Onboarding
Automate the entire first-day setup:
1. Clone repository
2. Install dependencies
3. Setup database
4. Configure IDE
5. Create welcome documentation
6. Run first test to verify setup
Include troubleshooting for common issues and links to key documentation.
Every developer who joins your team uses this. It’s consistent, comprehensive, and catches setup issues before the developer spends 2 hours wondering why tests won’t run. The difference between a developer being productive in 2 hours vs 2 days is literally this one command.
The Release Command
---
name: release
description: Prepare and execute release
usage: /release major|minor|patch
---
# Release Process
Handles the entire release workflow:
1. Verify all tests pass
2. Bump version (semver)
3. Generate changelog
4. Create release commit
5. Tag in Git
6. Build artifacts
7. Upload to registry
8. Update documentation
Provide confirmation prompts before irreversible steps.
This is where custom commands really shine. Releases are inherently complex and error-prone when done manually. A single /release major command handles it all consistently. You’re not trying to remember 8 steps while doing them. You’re not missing a step because you forgot something. You’re not accidentally doing them in the wrong order.
The Security Sync Command
---
name: security-check
description: Comprehensive security verification
usage: /security-check [--fix]
---
# Security Verification
Run complete security audit:
1. Dependency vulnerability scan
2. Secret detection (find exposed API keys)
3. SAST analysis (static code analysis)
4. Dependency license compatibility
5. Known vulnerability database check
If `--fix`, attempt automatic remediation. Otherwise just report.
Run this before every deployment. It catches vulnerabilities automatically instead of waiting for a security audit months later. The --fix option makes patching dependencies trivial. You prevent security incidents before they happen.
Sharing Commands Across Your Team
This is the beautiful part: your custom commands live in .claude/commands/ which is version-controlled. That means your entire team gets them through Git.
Team Command Workflow
- Developer creates custom command: Saves to
.claude/commands/my-command.md - Commits to repository:
git add .claude/commands/&&git commit - Team pulls changes: Next
git pull, everyone has the command - Team uses the command:
/my-commandavailable to all
No manual distribution, no emails, no copying files. Just Git doing what it does best. Your commands evolve with your team. Someone improves the /deploy command? Everyone gets the improvement next pull. Someone catches a bug in the /test command? Fix it once, benefit forever.
Best Practices for Shared Commands
- Clear descriptions: Your teammates need to understand what the command does. Not everyone reads code the same way.
- Parameter validation: Check that required arguments are provided. Tell users what went wrong, not just that it failed.
- Error handling: If something goes wrong, explain what happened and how to fix it. Don’t just error out silently.
- Exit feedback: Show what the command accomplished. “Deployed to staging. Health checks passed. Team notified” is better than silent success.
- Version safely: Test custom commands locally before pushing. Run them in your development environment first.
- Document edge cases: Comment on tricky parts of your command logic. Future you will thank current you.
Invoking Commands Programmatically
You can chain commands and reference them in your Claude Code operations:
/init my-project && /setup-local && /feature initial-setup
Commands execute sequentially. If one fails, the chain stops. This is powerful—you can create multi-step workflows that are atomic. Either the whole thing succeeds or nothing happens.
Command Precedence and Conflicts
If you have both a built-in command and a custom command with the same name, Claude Code prioritizes custom commands. This lets you override built-in behavior if needed—though usually you’ll want to use different names.
Aliases help avoid conflicts too. If you want a shorter version of a command, use the aliases field in your frontmatter. /rq becomes an alias for /review-quick.
Debugging Custom Commands
When your custom command doesn’t work as expected:
- Run
/helpto verify: Make sure Claude Code found your command file - Check frontmatter: YAML syntax errors break everything
- Test parameters: Ensure
$ARGUMENTSis parsing correctly - Review logic: Read through the command steps carefully
- Check permissions: Some operations need explicit approval
The /help command shows custom commands with their metadata, which helps diagnose issues. If /help doesn’t show your command, it’s definitely a syntax problem in the frontmatter.
Advanced: Conditional Logic in Commands
Custom commands support conditional logic based on your environment:
---
name: deploy
---
# Deploy with Conditions
If environment is production:
- Require explicit confirmation
- Run full test suite
- Create backup
- Deploy with zero-downtime
If environment is staging:
- Skip confirmation
- Run basic tests
- Deploy quickly
- Alert team
Parse environment from `$ARGUMENTS` and execute appropriate path.
You can use Claude Code’s conditional execution to adapt behavior based on context. This is how you make commands safe and flexible at the same time.
Environment Variables in Commands
Access environment information within your commands:
---
name: env-check
---
# Check Environment
Your command can reference:
- **$CWD**: Current working directory (/Users/dev/project)
- **$PROJECT**: Project root
- **$USER**: Current user (dev)
- **$BRANCH**: Current Git branch (feature/auth)
- **$CI**: Whether running in CI environment
- **$DEBUG**: Debug mode flag
Example: Only run migrations in non-CI environments unless explicitly forced.
This lets your commands behave differently based on context. A /test command might skip slow integration tests in CI but run everything locally. A /deploy command might skip confirmations in CI but require them when run locally.
Capturing Command Output
Your commands can chain and reference results:
/init my-app && /setup-local && /feature auth && /test
Each command’s output becomes input for the next. If /test fails, the chain stops. This creates guaranteed-correct workflow sequences. You don’t have to manually verify each step works—the chain enforces it.
Exit Codes and Error Handling
Commands should always indicate success or failure:
---
name: validate
---
# Validate Configuration
Exit with status:
- **0**: All validation passed
- **1**: Configuration invalid
- **2**: File not found
- **3**: Permission denied
Users can chain with && (continue on success) or || (fallback on failure).
Proper exit codes enable robust command chaining and error recovery. Your scripts can handle failures gracefully.
Logging and Audit Trails
All custom commands are automatically logged:
~/.claude/logs/commands.log
Contains:
- Timestamp of execution
- User who ran the command
- Arguments passed
- Exit code
- Duration
- Output summary
This creates an audit trail. If something went wrong in production, you can check who deployed what and when. This is critical for compliance and debugging.
Troubleshooting Common Issues
Even with slash commands, you’ll run into edge cases. Here’s how to handle them.
Command Not Found
You’ve created a command file but /help doesn’t show it. Check:
- File location: Is it in
.claude/commands/? - File extension: Must be
.md - Frontmatter: Is the
name:field set correctly? - Syntax: Run
/validate-commandto check YAML syntax - Case sensitivity: Command names are lowercase
If all else fails, restart Claude Code and run /help again. The command cache might be stale.
Arguments Not Parsing
Your command uses $ARGUMENTS but values aren’t coming through. Remember:
$ARGUMENTScontains everything after the command name- It’s not automatically parsed—you parse it within the command
- For
--flags, check your parsing logic - Use quotes for arguments with spaces:
/command "multi word argument"
Permissions Issues
Some commands need elevated permissions. If you see “Permission denied”:
- Check that the command includes approval prompts for risky operations
- Verify the user has necessary file system permissions
- Some operations (like production deployments) require explicit user confirmation—this is intentional
Performance Problems
Slow commands? Optimize by:
- Reduce scope: Instead of
/test(all tests), do/test auth-module - Cache results: Don’t re-run expensive operations
- Parallelize: Run independent checks in parallel
- Profile: Use
/profileto find bottlenecks
Getting Started: Your 5-Minute Action Plan
Ready to start using slash commands? Here’s what to do right now:
Minute 1-2: Explore built-ins
/help
/plan learn slash commands
Minute 3-4: Create your first custom command
Save this to .claude/commands/hello.md:
---
name: hello
description: Simple test command
usage: /hello [name]
---
# Hello Command
This is a test command that greets you.
If `$ARGUMENTS` is provided, greet that person. Otherwise, greet the user.
Minute 5: Use it
/hello
/hello Alice
You’ve now created and used a custom command. That’s the hardest part—once you know how, creating more gets easier.
Next Steps (After 5 Minutes)
- Look at the cookbook commands and adapt one for your workflow
- Commit your first command to
.claude/commands/ - Have your team run
/helpto see your new command - Celebrate your first automation win
Advanced Topics Worth Exploring
Once you’re comfortable with basics:
- Command composition: Build complex workflows by chaining commands
- Dynamic help: Have your commands update their own documentation
- Integration hooks: Trigger commands from Git hooks (pre-commit, post-push, etc.)
- Team governance: Establish standards for what commands should do
- Metrics and monitoring: Track which commands are most used and optimize them
- Versioning: Tag command releases and manage backwards compatibility
The Philosophy Behind Slash Commands
At their core, slash commands are about codifying best practices. Every time you create a /deploy command instead of documenting “how to deploy” in a wiki, you’re:
- Making deployment explicit and discoverable
- Reducing the chance of human error
- Creating an audit trail
- Ensuring consistency across the team
- Making onboarding faster (new devs just run the command)
This is why teams using slash commands effectively show 30-40% improvements in deployment speed and 50%+ reductions in production incidents. You’re not just saving time; you’re building reliability and consistency into your workflow.
Summary
Slash commands are where Claude Code’s true power lives. The built-in commands handle your everyday needs—help, clearing, testing, reviewing. But custom commands? Those are where you build your unique workflow that fits your exact needs and your team’s specific challenges.
Start with the built-ins. Get comfortable with /help, /plan, and /review. Then create one custom command that solves a real problem in your workflow. Share it with your team through .claude/commands/. Watch how it spreads and evolves.
Whether you’re managing deployments, onboarding developers, running security checks, or generating documentation, there’s a slash command ready to do it. And if there isn’t, you can create one in minutes.
That’s the magic of slash commands: a small investment in automation that compounds into massive efficiency gains across your entire team.
Now go /help yourself to greatness.
—iNet