Skip to content

Creating Custom Commands

Custom commands are the cornerstone of workflow automation in Claude Code. By encapsulating complex tasks into reusable commands, you transform repetitive work into single-line instructions that any team member can execute.

Consistency

Ensure everyone follows the same workflows and best practices

Efficiency

Turn multi-step processes into instant commands

Knowledge Sharing

Capture expertise in shareable, version-controlled commands

Onboarding

New team members become productive immediately

Commands live in specific directories based on their scope:

  • Directory.claude/
    • Directorycommands/ # Project-specific (shared via Git)
      • deploy.md # /deploy or /project:deploy
      • test.md # /test or /project:test
      • Directorybackend/
        • migrate.md # /backend:migrate
  • Directory~/.claude/
    • Directorycommands/ # Personal (all projects)
      • review.md # /review or /user:review
      • format.md # /format or /user:format

Every command is a Markdown file with optional YAML frontmatter:

---
# Optional frontmatter
allowed-tools: Edit, Bash(npm:*), Read
description: Deploy application to staging
argument-hint: [environment] [--skip-tests]
---
# Command Title
Your prompt content here, with $ARGUMENTS placeholder
for dynamic input.
## Optional sections
- Requirements
- Steps
- Context
  1. Identify a repetitive task Think about what you do multiple times daily

  2. Create the command file

    Terminal window
    mkdir -p .claude/commands
    touch .claude/commands/pr-review.md
  3. Write the command

    # Review PR for: $ARGUMENTS
    Please review the changes and provide feedback on:
    1. Code quality and best practices
    2. Potential bugs or edge cases
    3. Performance implications
    4. Security concerns
    5. Test coverage
    Focus on actionable feedback, not style issues.
  4. Test the command

    Terminal window
    /pr-review authentication module

Load context dynamically using bash execution:

---
allowed-tools: Bash(git:*), Read, Edit
description: Smart commit with context
---
# Create Commit
## Current Status
- Branch: !`git branch --show-current`
- Changed files: !`git status --short`
- Last commit: !`git log -1 --oneline`
## Staged Changes
!`git diff --cached`
## Task
Create a descriptive commit message for these changes.
Consider: $ARGUMENTS
Follow conventional commit format:
- feat: new feature
- fix: bug fix
- docs: documentation
- refactor: code restructuring
- test: adding tests
- chore: maintenance

Create commands that orchestrate complex processes:

---
allowed-tools: Bash(npm:*), Edit, MultiEdit, Task
description: Complete feature implementation workflow
argument-hint: feature-name
---
# Implement Feature: $ARGUMENTS
Execute this complete workflow:
## 1. Setup
- Create feature branch: `feature/$ARGUMENTS`
- Update dependencies if needed
## 2. Implementation
- Review requirements in @docs/features/$ARGUMENTS.md
- Implement following our patterns in @src/patterns.md
- Ensure TypeScript types are properly defined
## 3. Testing
- Write unit tests achieving >80% coverage
- Add integration tests for API endpoints
- Include edge cases and error scenarios
## 4. Documentation
- Update API documentation
- Add JSDoc comments
- Create usage examples
## 5. Finalization
- Run full test suite
- Ensure linting passes
- Create PR with detailed description
Stop and notify me if any step fails.

Build smart commands that adapt to context:

---
allowed-tools: Read, Edit
description: Add header comments based on file type
---
# Add File Headers
## Detect File Type
File: $ARGUMENTS
Extension: !`echo "$ARGUMENTS" | rev | cut -d'.' -f1 | rev`
## Apply Appropriate Header
Based on the extension above:
- If .js/.ts: Add JSDoc header with @module
- If .py: Add docstring with module description
- If .sh: Add shebang and usage documentation
- If .md: Add frontmatter with title and date
- Otherwise: Add appropriate comment style
Include:
- Purpose description
- Author: !`git config user.name`
- Date: !`date +%Y-%m-%d`
- License: MIT

Create commands that generate boilerplate:

---
allowed-tools: Write, MultiEdit
description: Generate React component with tests
argument-hint: ComponentName [--hooks] [--typescript]
---
# Generate React Component: $ARGUMENTS
Parse arguments to extract:
- Component name (PascalCase)
- Whether to use hooks (--hooks flag)
- Whether to use TypeScript (--typescript flag)
Generate:
1. Component file at `src/components/{ComponentName}/index.{tsx|jsx}`
2. Test file at `src/components/{ComponentName}/__tests__/index.test.{tsx|jsx}`
3. Storybook file at `src/components/{ComponentName}/index.stories.{tsx|jsx}`
4. Styles at `src/components/{ComponentName}/styles.module.css`
Follow patterns from existing components in @src/components/Button

Clear & Actionable

/deploy-staging/fix-formatting/process/handle

Consistent Patterns

  • Actions: verb-noun
  • Queries: get-noun
  • Generators: create-noun
  • Workflows: workflow-name
# Robust Argument Parsing
Parse arguments: $ARGUMENTS
Expected format: [action] [target] [--flags]
- Action: ${1:-default-action}
- Target: ${2:-all}
- Flags: Extract any --flag patterns
Validate:
- Action must be: create|update|delete
- Target must exist in project
- Flags are optional

Build resilient commands:

---
allowed-tools: Bash(test:*), Task
---
# Safe Deployment
## Pre-flight Checks
- Tests passing: !`npm test &>/dev/null && echo "✓" || echo "✗"`
- No uncommitted changes: !`[[ -z $(git status --porcelain) ]] && echo "✓" || echo "✗"`
- Valid environment: !`[[ -f .env.$ARGUMENTS ]] && echo "✓" || echo "✗"`
## Decision
If any check shows ✗:
- Report which checks failed
- Suggest fixes
- DO NOT proceed with deployment
Otherwise, continue with deployment to $ARGUMENTS

Chain commands for complex workflows:

# Orchestrate Multiple Commands
Please execute these commands in sequence:
1. Run tests: `/test:unit --coverage`
2. If passing, update docs: `/generate:docs`
3. Create release: `/release:prepare $ARGUMENTS`
4. Deploy: `/deploy:staging`
Abort on any failure.
---
allowed-tools: Write
description: Generate custom command from description
---
# Command Generator
Based on this description: $ARGUMENTS
1. Analyze what the command should do
2. Determine required tools
3. Create command file with:
- Appropriate frontmatter
- Clear description
- Robust implementation
- Error handling
Save to: .claude/commands/generated/[appropriate-name].md
---
allowed-tools: Bash(git:*), Task
description: Apply changes across multiple repos
---
# Multi-Repo Update: $ARGUMENTS
## Repositories
!`cat ~/.claude/team-repos.txt`
For each repository above:
1. Clone if not present
2. Create branch: `chore/$ARGUMENTS`
3. Apply the change specified
4. Commit with standardized message
5. Push and create PR
Use Task for parallel execution where possible.
  • Directory.claude/commands/
    • Directorydev/
      • start.md # Start dev environment
      • stop.md # Graceful shutdown
      • reset.md # Reset to clean state
      • seed.md # Seed with test data
.claude/commands/test/smart.md
---
allowed-tools: Bash(npm:*), Read
description: Intelligently run relevant tests
---
# Smart Test Runner
## Analyze Changes
- Modified files: !`git diff --name-only`
- File types: !`git diff --name-only | sed 's/.*\.//' | sort -u`
## Test Strategy
Based on changes:
- If *.test.* modified: Run those specific tests
- If source files: Find and run corresponding tests
- If config files: Run all tests
- If no changes: Run tests for $ARGUMENTS
Include:
- Coverage report
- Performance metrics
- Failure analysis with fix suggestions
.claude/commands/docs/api.md
---
allowed-tools: Read, Write, Bash(npm:*)
description: Generate API documentation
---
# Generate API Documentation
Target: ${ARGUMENTS:-all endpoints}
1. Scan for API endpoints in @src/api/
2. Extract:
- Route definitions
- Request/response types
- Authentication requirements
- Rate limits
3. Generate OpenAPI spec
4. Create Markdown documentation
5. Update Postman collection
6. Verify examples work
Output to: docs/api/
Terminal window
# Share team commands
git add .claude/commands/
git commit -m "Add team workflow commands"
git push
# Team members get them automatically
git pull
/help # New commands appear!

Create a command index:

.claude/commands/README.md
# Team Claude Commands
## Development
- `/dev:start` - Start development environment
- `/dev:reset` - Reset database and cache
## Testing
- `/test:smart` - Run relevant tests
- `/test:e2e` - Run end-to-end suite
## Deployment
- `/deploy:staging` - Deploy to staging
- `/deploy:rollback` - Rollback last deployment
## Utilities
- `/lint:fix` - Fix all linting issues
- `/deps:update` - Update dependencies safely
  1. Limit tool permissions in frontmatter
  2. Validate inputs before using in commands
  3. Avoid executing arbitrary user input
  4. Use read-only tools when possible
  5. Document risks in command description
---
# Explicitly limit tools
allowed-tools: Read, Bash(ls:*), Bash(grep:*)
description: Search for patterns (read-only)
---
# Safe Search: $ARGUMENTS
Search for pattern in allowed directories only:
- src/
- docs/
- tests/
Do NOT search in:
- .env files
- .git/
- node_modules/
- Any file containing 'secret' or 'key'
Use grep with --exclude patterns for safety.

Enhance your custom commands with:

  1. Hooks Integration - Trigger commands automatically
  2. Memory Management - Make commands context-aware
  3. MCP Servers - Extend commands with external tools