Claude Code Mastery Guide Part 4: Custom Commands for Eliminating Repetitive Typing
Welcome to the fourth installment of the Claude Code Mastery Guide. This article unlocks a productivity-boosting feature that will double your efficiency: Custom Commands. Transform those repetitive instructions and complex workflows you type daily into simple slash commands, freeing yourself from manual repetition forever.
The Problem: Repetitive Command Fatigue
Have you experienced these scenarios?
- "Please check my code style using Google Java Format"
- "Generate test cases using JUnit 5 and Mockito, cover all branches, name test classes xxxTest"
- "Review the modified code and generate a report"
- And countless variations...
Doing this once or twice is manageable, but typing these instructions daily becomes exhausting. Imagine if these operations could become single slash commands—/test automatically generates unit tests, or /build runs compilation plus testing. How liberating would that be?
Claude Code's Custom Commands feature exists precisely for this purpose.
What Are Custom Commands?
Simply put, custom commands package frequently used prompts, instructions, or even scripts into快捷 slash commands starting with /.
For example, create a /test command containing:
Please generate JUnit 5 unit tests for the currently open Java class, covering main branches, using Mockito to mock dependencies. Place test classes in `src/test/java` with `Test` suffix added to class names.Afterward, simply typing /test in Claude Code automatically generates tests following this pattern—no need to repeat the verbose instructions each time.
Creating Custom Commands: The Basics
Step-by-Step Setup
- Create a
commandsfolder in your project root directory or globally at~/.claude/ - Inside this folder, create a file named after your command (e.g.,
test.mdfor/test) - Write your instructions in the file
Example: test.md
Write JUnit 5 unit tests for the currently open file.
Requirements:
- Use JUnit 5 and Mockito
- Cover main business branches
- Test class name = original class name + "Test"
- Place in corresponding package path under src/test/java
- Mock external dependencies, avoid real network requestsIn your Claude Code session, simply type /test, and Claude reads this file and executes according to your specifications.
That's it. No complex configuration, no coding required.
Advanced Technique 1: Accepting Command Arguments
Command files can use the $ARGUMENTS placeholder to receive user-provided arguments.
Example with arguments:
Generate complete unit tests for the following code.
Requirements:
- Use JUnit 5 and Mockito
- Cover main business branches
- Test class name = original class name + "Test"
- Place in corresponding package path under src/test/java
- Mock external dependencies, avoid real network requests
$ARGUMENTSNow typing /test path/to/SpecificFile.java executes the command against that specific file or directory.
Beyond $ARGUMENTS, Claude Code CLI also supports positional parameters:
$1: First argument$2: Second argument$ARGUMENTS: Entire argument string
Advanced Technique 2: Adding YAML Frontmatter
You can add YAML frontmatter at the top of your .md file to control command behavior (description, arguments, execution scripts, etc.).
Example with YAML frontmatter:
---
description: "Generate unit tests"
argument-hint: <file or directory path>
---
Write JUnit 5 unit tests for the following code.
Requirements:
- Use JUnit 5 and Mockito
- Cover main business branches
- Test class name = original class name + "Test"
- Place in corresponding package path under src/test/java
- Mock external dependencies, avoid real network requests
$ARGUMENTSNow typing /test OrderService automatically generates unit tests for OrderService.
Note: The YAML frontmatter (description and argument-hint) is optional but highly recommended. Adding these displays helpful command descriptions and parameter hints when you type /test, significantly improving usability.
Additional YAML Configuration Options
Beyond description and argument-hint, Claude Code supports more configuration:
- allowed-tools: Whitelist of tools this command can use
- model: Force execution using a specific model
- context: fork: Execute in an isolated sub-agent, avoiding main conversation pollution
- agent: Specify which sub-agent should execute this command
Special mention: the model field is particularly practical. For simple commands like /commit (generating commit messages), there's no need to use the most powerful (and expensive) Opus model—specifying Haiku is sufficient, providing faster responses at lower cost.
Advanced Technique 3: Executing Local Scripts
Custom commands aren't limited to sending prompts—they can directly execute scripts on your computer.
Specify the execute field in YAML:
---
execute: "scripts/run-tests.sh"
---Claude Code runs this script and displays the output. For instance, write a deploy.sh script, then typing /deploy enables one-click deployment to your test environment.
Advanced Technique 4: The /simplify Command
/simplify is a built-in Claude Code command designed for proactive code diagnosis and optimization. Its core purpose is identifying issues and directly implementing improvements.
How it works: The command launches 3 parallel agents analyzing code from three dimensions:
- Reusability: Identifying code duplication and abstraction opportunities
- Quality: Finding code smells, anti-patterns, and maintainability issues
- Efficiency: Detecting performance bottlenecks and optimization opportunities
The power lies in parallelism: Instead of solving problems sequentially, three agents work simultaneously from different angles, naturally doubling efficiency.
Important caution: This command directly modifies your files. After executing /simplify, always review changes with git diff to ensure modifications align with your expectations before committing.
For developers, this command is essential knowledge and should be used regularly.
Advanced Technique 5: The /review Command
/review serves a complementary but distinct purpose from /simplify. Its core objective is analyzing existing code changes and generating reports that highlight potential risks, typically without directly modifying code.
How it works: /review analyzes code or Git diffs to provide comprehensive code review reports covering:
- Risk assessment
- Identified problems
- Improvement recommendations
When to use: Run /review after creating a Pull Request, targeting your PR's changes. Think of it as a colleague performing a code review, ensuring no logical errors or architectural issues were missed before sending the PR to your team.
Key distinction:
/simplify= Proactive optimization (modifies code)/review= Retrospective analysis (generates report)
Practical Examples
Example 1: /build — One-Click Compile and Test
---
description: "Compile and run all unit tests"
---
Please execute the following commands:
1. `mvn clean compile` — Compile the project
2. `mvn test` — Run all unit tests
If compilation or testing fails, please analyze error causes and provide fix recommendations.Example 2: /checkstyle — Code Style Verification
---
description: "Check if code style meets team standards"
---
Please check if the currently open Java file meets the following standards:
- Class names use UpperCamelCase
- Methods do not exceed 50 lines
- All public methods have JavaDoc
- Prohibit `System.out.println`, must use logger
- If violations exist, provide specific locations and modification suggestionsExample 3: /doc — Component Documentation Generation
---
description: "Generate standard technical documentation for selected component/class"
argument-hint: <file or directory path>
---
Please generate complete technical documentation for $ARGUMENTS.
## Document Structure Requirements
1. **Overview:** One-sentence description of component/class functionality
2. **API List:**
- For frontend components: List Props / Slots / Events / Methods
- For backend Java classes: List public methods, parameters, return values, exceptions
3. **Usage Examples:** At least one complete minimal example code
4. **Notes:** Performance, compatibility, dependencies, or common errors
## Output Format
Use Markdown with headers, tables (for APIs), and code blocks (for examples).
## Additional Rules
- Read actual code from currently open file or passed $ARGUMENTS parameter
- If code cannot be accessed, prompt user to provide file path or paste code
- For TypeScript components, infer Props types from type definitions first
- For Java classes, use JavaDoc comments as documentation foundation, automatically supplementing undocumented methodsExample 4: /commit — Automated Commit Generation
---
description: Automatically commit current changes
allowed-tools: Bash(git status:*), Bash(git diff:*), Bash(git add:*), Bash(git commit:*)
model: claude-3-5-haiku-20241022
---
## Context
- Current git status: !`git status`
- Current change details: !`git diff HEAD`
## Task
Based on the above changes, generate a standardized commit message and commit.
Format requirements: type(scope): description
- type: feat / fix / docs / refactor / test / chore
- scope: Modified module (e.g., blog, auth, api)
- description: Brief English description
$ARGUMENTSBest Practices and Recommendations
Command Organization
- Keep command files focused and specific
- Use descriptive filenames matching command names
- Group related commands in subdirectories if needed
- Document complex commands with clear examples
Model Selection Strategy
- Use smaller, faster models (Haiku) for simple tasks
- Reserve powerful models (Opus) for complex reasoning
- Consider cost implications for frequently-used commands
Security Considerations
- Carefully review
allowed-toolswhitelists - Avoid commands that execute arbitrary user input
- Test commands thoroughly before sharing with teams
Conclusion
Custom Commands transform Claude Code from a conversational AI into a personalized productivity powerhouse. By investing time upfront to create well-crafted commands, you eliminate repetitive typing, ensure consistency across operations, and free mental energy for higher-value work.
Start with your most frequent operations, create commands for them, and gradually build your personalized command library. Your future self will thank you.