โŒ˜ K
Claude Code CLI Tips & Tricks

Claude Code Guide

Unlock the full power of Claude Code CLI with expert tips, hidden features, and productivity hacks.

$ claude
โ€บ ultrathink - How to scale this architecture?
๐Ÿง 
Extended Thinking
Automatic deep reasoning (formerly Ultrathink)
โš ๏ธ Breaking Change (v2.0.x)
Since Claude Code v2.0.x, extended thinking is enabled by default. The magic words (think, ultrathink, etc.) are now deprecated. See #19098 for details.

Extended thinking allows Claude to reason through complex problems with up to 31,999 tokens of internal reasoning. Previously triggered by magic words, it's now automatic.

How It Works Now

Method Status Notes
think Deprecated No longer triggers extended thinking
ultrathink Deprecated No longer triggers extended thinking
Automatic Active Thinking enabled by default in v2.0.x+
MAX_THINKING_TOKENS Supported Environment variable to control budget
# Set maximum thinking tokens (overrides automatic behavior) export MAX_THINKING_TOKENS=10000 # Or per-session MAX_THINKING_TOKENS=32000 claude
โœ“
Current Behavior
  • Thinking is automatic for complex tasks
  • Claude decides when to think deeply
  • Use MAX_THINKING_TOKENS to override
โœ—
No Longer Works
  • think keyword
  • think hard / megathink
  • ultrathink
๐Ÿ“ Community Feedback
Some users report quality changes since automatic thinking was introduced. Track the discussion at GitHub Issue #19098.
๐Ÿ“„
CLAUDE.md
Custom instructions for your projects

CLAUDE.md is a special markdown file that Claude Code reads automatically to understand your project context, coding standards, and preferences.

File Locations

Location Scope Priority
~/.claude/CLAUDE.md Global (all projects) Lowest
.claude/CLAUDE.md Project-specific Highest
CLAUDE.md Project root Medium
# Project: My App ## Tech Stack - TypeScript, React 18, Vite - TailwindCSS for styling - Vitest for testing ## Coding Standards - Use functional components - Prefer named exports - Always add JSDoc comments
  • ๐Ÿ’ก Include project architecture, tech stack, and coding conventions
  • ๐Ÿ’ก Add common commands like build, test, and lint
  • ๐Ÿ’ก Document file structure and naming patterns
  • ๐Ÿ’ก Use /init to generate a starter CLAUDE.md
โšก
Slash Commands
Quick actions with / prefix

Slash commands provide quick access to common actions and settings. Type / to see all available commands.

Essential Commands

Command Description
/compact Compress conversation context to save tokens
/cost Show token usage and estimated cost
/clear Clear conversation history
/init Generate CLAUDE.md for your project
/doctor Diagnose configuration issues
/config Open configuration settings
/help Show help and available commands
/review Review code changes or PR
/bug Report a bug to Anthropic
๐Ÿ’ก Pro Tip
Use /compact regularly in long sessions to reduce token usage and keep responses fast. It summarizes the conversation while preserving important context.
โŒจ๏ธ
Keyboard Shortcuts
Speed up your workflow

Master these keyboard shortcuts to navigate Claude Code like a pro.

Essential Shortcuts

Shortcut Action
Esc Interrupt current generation
Ctrl + C Cancel operation / Exit
Ctrl + D Exit Claude Code
Ctrl + L Clear terminal screen
โ†‘ / โ†“ Navigate command history
Tab Autocomplete file paths
Shift + Enter Multi-line input
โšก
Quick Actions
  • Esc to stop a long response
  • โ†‘ to repeat last command
  • Tab for file autocomplete
๐Ÿ”„
Model Switching
Choose between Sonnet, Opus, and Haiku

Claude Code supports different models optimized for different use cases. Choose based on your needs for speed, cost, or capability.

Available Models

Model Best For Speed Cost
Haiku Quick tasks, simple edits โšกโšกโšก Fastest ๐Ÿ’ฐ Lowest
Sonnet Balanced (default) โšกโšก Fast ๐Ÿ’ฐ๐Ÿ’ฐ Medium
Opus Complex reasoning, architecture โšก Slower ๐Ÿ’ฐ๐Ÿ’ฐ๐Ÿ’ฐ Highest
# Start with a specific model claude --model opus claude --model haiku
  • ๐Ÿ’ก Use Haiku for quick file edits and simple questions
  • ๐Ÿ’ก Use Sonnet (default) for most coding tasks
  • ๐Ÿ’ก Use Opus for complex architecture and deep analysis
๐Ÿช
Hooks
Automate actions before/after commands

Hooks let you run custom scripts automatically when Claude Code performs certain actions. Perfect for linting, testing, or custom workflows.

Hook Types

Hook Trigger
PreToolUse Before a tool executes
PostToolUse After a tool completes
Notification When Claude wants your attention
Stop When Claude finishes a response
{ "hooks": { "PostToolUse": [ { "matcher": "Write", "command": "npm run lint:fix $FILE" } ] } }
  • ๐Ÿ’ก Auto-format code after every file write
  • ๐Ÿ’ก Run tests after code changes
  • ๐Ÿ’ก Send notifications when tasks complete
๐Ÿค
Sub-agents
Delegate tasks to specialized agents

Sub-agents allow Claude to delegate complex tasks to specialized agents that run in isolated contexts. They enable parallelization, better context management, and domain-specific expertise.

Sub-agent Benefits

Benefit Description
Parallelization Run multiple tasks simultaneously
Context Isolation Each agent has its own context window
Specialization Fine-tuned instructions for specific domains
Tool Control Different tool access per agent type
# Code Reviewer Agent You are a specialized code review agent. Focus on: - Security vulnerabilities - Performance issues - Code style consistency Only report significant issues.

Built-in Agents

Agent Use Case
general-purpose Default agent for any task
Explore Fast codebase exploration
Plan Architecture and implementation planning
๐Ÿ’ก Context Management
Sub-agents only return their final results to the main context, keeping your primary conversation clean and focused. Great for complex tasks that would otherwise bloat context.
โœ…
Task Tools
Track progress with visible task lists

Task Tools allow Claude to create and manage visible task lists in the terminal. Track progress, show dependencies, and display real-time status with animated spinners.

Available Tools

Tool Description
TaskCreate Create a new task with subject, description, activeForm
TaskUpdate Update status (pending โ†’ in_progress โ†’ completed)
TaskList List all tasks with their current status
TaskGet Get details of a specific task
# Create task with spinner text TaskCreate({ subject: "Build release", description: "Build, sign and notarize", activeForm: "Building release..." # Shows in spinner })

Task Dependencies

Parameter Usage
blockedBy Task IDs that must complete first
addBlockedBy Add dependencies to existing task
# Task 2 waits for Task 1 TaskUpdate({ taskId: "2", addBlockedBy: ["1"] }) # Result in terminal: โœ“ #1 Create Issue โ— #2 Implement # (in_progress with spinner) โ˜ #3 Open PR [blocked by #2]
๐Ÿ’ก When to Use Tasks
Use tasks for multi-step workflows (3+ steps). For simple tasks, Claude can work directly without task tracking. Ask Claude to "create tasks for this workflow" to enable tracking.
๐Ÿ”Œ
MCP Servers
Extend Claude with external tools

Model Context Protocol (MCP) servers allow Claude Code to interact with external tools, databases, and APIs. Connect to GitHub, databases, or custom services.

Popular MCP Servers

Server Capabilities
GitHub Issues, PRs, repos, actions
PostgreSQL Query databases directly
Filesystem Extended file operations
Slack Send messages, read channels
Puppeteer Browser automation
{ "mcpServers": { "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_TOKEN": "your-token" } } } }
๐Ÿ“š Learn More
Find more MCP servers at github.com/modelcontextprotocol/servers
๐Ÿ”ฎ
Serena MCP
Semantic code navigation and memories

Serena is an MCP server that provides semantic code understanding through LSP integration. It enables symbol-level navigation, intelligent editing, and persistent project memories.

Key Features

Feature Description
Symbolic Tools find_symbol, replace_symbol_body, rename_symbol
Memories Persistent context stored in .serena/memories/
References Find all usages of a symbol across codebase
Multi-language TypeScript, Python, Swift, Go, and more
# Read a memory read_memory("project_overview") # Write a memory (persists between sessions) write_memory("current_work", "Working on feature X...") # List available memories list_memories()
# Find a symbol by name pattern find_symbol("MyClass/myMethod", include_body=True) # Replace entire symbol body replace_symbol_body("MyClass/myMethod", "func myMethod() { ... }") # Rename across codebase rename_symbol("oldName", "newName")
๐Ÿ’ก Memories Persist
Memories stored in .serena/memories/ survive between sessions. Use them for project context, current work status, and team conventions.
๐Ÿค–
Headless Mode
Non-interactive scripting and automation

Run Claude Code in headless mode for scripting, CI/CD pipelines, and automation. No interactive prompts needed.

# Single prompt claude -p "Explain this function" < file.js # With file input cat code.py | claude -p "Find bugs in this code" # Output to file claude -p "Generate tests" > tests.js
# GitHub Actions - name: Code Review run: | claude -p "Review changes for security issues" \ < $(git diff HEAD~1)
๐Ÿš€
Use Cases
  • Automated code review in CI
  • Generate changelogs
  • Batch file processing
  • Documentation generation
๐Ÿ”€
Git Integration
Smart commits, PRs, and reviews

Claude Code integrates seamlessly with Git for intelligent commits, PR reviews, and version control workflows.

Git Features

Feature How to Use
Smart Commits Ask Claude to commit with a meaningful message
PR Review /review or ask to review changes
Diff Analysis Paste diff or ask about changes
Conflict Resolution Ask Claude to resolve merge conflicts
# Ask Claude to commit > Commit these changes with a good message # Review a PR > /review # Analyze changes > What changed in the last 5 commits?
โš ๏ธ Safety
Claude never pushes to remote without explicit permission. Always review commits before pushing.
๐Ÿ’ฐ
Costs & Performance
Monitor and optimize token usage

Keep track of your token usage and costs, and learn how to optimize for efficiency.

Cost Optimization Tips

Strategy Impact
/compact regularly Reduces context size by 50-80%
Use Haiku for simple tasks 10x cheaper than Opus
Clear with /clear Start fresh, no accumulated tokens
Be specific in prompts Fewer back-and-forth exchanges
# View current session costs > /cost # Compact to reduce context > /compact
๐Ÿ“Š Token Pricing (approximate)
Haiku: ~$0.25/1M input, $1.25/1M output
Sonnet: ~$3/1M input, $15/1M output
Opus: ~$15/1M input, $75/1M output
๐Ÿ’ป
IDE Integrations
VS Code, JetBrains, Vim, and more

Claude Code works in your terminal, but also integrates with popular IDEs for an enhanced experience.

Supported IDEs

IDE Integration
VS Code Terminal panel, integrated commands
JetBrains IntelliJ, WebStorm, PyCharm terminal
Vim / Neovim Terminal mode, buffer integration
Zed Native terminal support
  • ๐Ÿ’ก VS Code: Open terminal with Ctrl+` and run claude
  • ๐Ÿ’ก Vim: Use :term claude to open in split
  • ๐Ÿ’ก Tmux: Create a dedicated Claude pane
โš™๏ธ
Configuration & /doctor
Settings and troubleshooting

Configure Claude Code to match your workflow and diagnose issues with the built-in doctor command.

Configuration Files

File Purpose
~/.claude/settings.json Global settings (model, hooks, MCP)
.claude/settings.json Project-specific settings
CLAUDE.md Project instructions
# Diagnose configuration issues > /doctor # Output shows: โœ“ API key configured โœ“ Model access verified โœ“ MCP servers connected โš  CLAUDE.md not found (optional)

Environment Variables

Variable Purpose
ANTHROPIC_API_KEY Your API key
CLAUDE_MODEL Default model
MAX_THINKING_TOKENS Override thinking budget
๐Ÿ“Š
Context Management
Optimize your 200K token context window

Claude Code has a 200K token context window (500K for Enterprise, 1M beta). Learn to manage it effectively for optimal performance on long-running tasks.

Context Strategies

Strategy When to Use
/compact When context exceeds 50% - summarizes while preserving key info
/context Check current context usage mid-session
Sub-agents Isolate complex tasks to separate context windows
@ Mentions Load files on-demand instead of all at once
# Check context usage > /context # Compact before hitting limits > /compact # Use sub-agents for complex tasks > Use a sub-agent to analyze all test files
โœ“
Best Practices
  • Be specific - avoid "fix my app"
  • Use @ mentions for targeted context
  • Compact at ~50% usage, not 90%
  • Keep CLAUDE.md minimal
โœ—
Avoid
  • Loading entire codebase at start
  • Long back-and-forth conversations
  • Waiting until context is full
  • Ignoring compaction warnings
๐Ÿ“ˆ Performance Impact
Quality degrades as context fills. Keep 25% free (50K tokens) for reasoning. Compact triggers at 75% to leave room for high-quality responses.
๐Ÿง 
Memory
Persistent context across sessions

Claude Code uses a hierarchical memory system through CLAUDE.md files to remember preferences, project context, and instructions across sessions.

Memory Hierarchy

Level Location Scope
Enterprise Organization policy IT rules, compliance
Project .claude/CLAUDE.md Team instructions
Project Rules .claude/rules/ Modular rule files
User ~/.claude/CLAUDE.md Personal preferences
# Project Memory ## Tech Stack - TypeScript, React 18, Vite - Jest for testing ## Commands - Build: npm run build - Test: npm run test ## Style - Use functional components - Prefer named exports
  • ๐Ÿ’ก Start minimal - add to CLAUDE.md based on what Claude gets wrong
  • ๐Ÿ’ก Store detailed docs in docs/ folder, reference with @ when needed
  • ๐Ÿ’ก Use /init to bootstrap a CLAUDE.md for your project
  • ๐Ÿ’ก Team-shared instructions go in project, personal prefs in ~/.claude/
@
@ Mentions
Reference files and folders directly in prompts

Use @ mentions to reference files, folders, or URLs directly in your prompts. Claude will automatically read and understand the content.

Mention Types

Syntax What it does
@file.ts Reference a specific file
@src/ Reference an entire folder
@https://... Fetch and reference a URL
@git:branch Reference a git branch diff
# Reference a file > Explain what @src/utils/auth.ts does # Compare with URL > Compare @package.json with @https://example.com/package.json # Folder context > Review all files in @src/components/
๐Ÿ’ก Pro Tip
Use Tab for autocomplete when typing file paths. Claude will suggest matching files and folders.
๐Ÿ”
Permissions & Safety
Control what Claude can do automatically

Claude Code asks for permission before making changes. You can configure trust levels and auto-accept behaviors.

Permission Levels

Action Default Behavior
Read files Always allowed
Write/Edit files Asks permission
Run commands Asks permission
Delete files Always asks
# Accept all edits for this session > Type a when prompted (accept all) # Start with auto-accept claude --dangerously-skip-permissions
โœ“
Quick Responses
  • y - Yes, allow this action
  • n - No, deny this action
  • a - Accept all (this session)
  • e - Edit before accepting
โš ๏ธ Safety Warning
Be careful with --dangerously-skip-permissions. Only use in trusted environments or for automated scripts.
๐Ÿ”„
Session Resume
Continue conversations across sessions

Claude Code saves your conversation history. You can resume previous sessions to continue where you left off.

# Resume the most recent session claude --resume # Or use the slash command > /resume # Continue last conversation (alias) claude -c

Session Management

Command Description
/resume Show list of recent sessions
claude --resume Resume most recent session
claude -c Continue last conversation
  • ๐Ÿ’ก Sessions are saved per-project directory
  • ๐Ÿ’ก Use /compact before resuming long sessions
  • ๐Ÿ’ก Session history helps Claude remember context
๐Ÿ–ผ๏ธ
Image Support
Analyze screenshots and images

Claude can see and analyze images! This is incredibly useful for debugging UI issues, understanding designs, or extracting information from screenshots.

Supported Formats

Format Use Case
PNG Screenshots, UI mockups
JPG/JPEG Photos, designs
GIF Simple graphics
WebP Modern web images
PDF Documents with images
# Reference an image file > What's wrong with the UI in @screenshot.png? # Debug from error screenshot > Fix the error shown in @error.png # Implement from design > Create this component based on @design.png
๐Ÿš€
Use Cases
  • Debug UI bugs from screenshots
  • Implement designs from mockups
  • Analyze error messages
  • Extract text from images
โŒจ๏ธ
Vim Mode
Vim keybindings for the input

Love Vim? Claude Code has optional Vim keybindings for the input field. Navigate, edit, and write prompts using familiar Vim motions.

# In settings.json { "inputMode": "vim" } # Or via /config > /config

Supported Vim Commands

Command Action
i Insert mode
Esc Normal mode
h/j/k/l Navigation
w/b Word navigation
dd Delete line
yy/p Yank/Paste
๐Ÿ’ก Tip
This only affects the input field. Claude's responses and file editing use the standard interface.
๐Ÿ› ๏ธ
Custom Slash Commands
Create your own /commands

Create custom slash commands to automate repetitive prompts. Define templates that expand when you type them.

{ "customCommands": { "/test": "Run all tests and fix any failures", "/pr": "Create a PR with a detailed description", "/refactor": "Refactor this code for better readability", "/doc": "Add JSDoc comments to all functions" } }

Command Variables

Variable Expands To
$FILE Current file path
$SELECTION Selected text (if any)
$PROJECT Project root path
  • ๐Ÿ’ก Commands are project-specific when in .claude/settings.json
  • ๐Ÿ’ก Global commands go in ~/.claude/settings.json
  • ๐Ÿ’ก Use for team-shared workflows
โšก
Custom Skills
Complex reusable prompts with /skill-name

Skills are more powerful than custom commands. They can include multi-step instructions, trigger specific behaviors, and create complete workflows invoked with a simple /skill-name.

{ "workflow": { "description": "Full development workflow", "prompt": "Execute the development workflow:\n1. Create tasks for all steps\n2. Create GitHub issue\n3. Implement with feature branch\n4. Open PR\n5. Wait for tests\n6. Release" }, "review": { "description": "Code review current changes", "prompt": "Review staged changes for bugs, security issues, and style" } }

Skills vs Commands

Aspect Custom Commands Custom Skills
Location settings.json skills.json
Complexity Simple text expansion Multi-step workflows
Description Not shown Shown in help
Best For Quick shortcuts Complex processes
# Invoke a skill /workflow Fix authentication bug # Skill expands to full prompt and executes
๐Ÿ’ก Restart Required
After creating or modifying ~/.claude/skills.json, restart Claude Code for changes to take effect.
๐Ÿ“‹
Plan Mode
Design before implementing

Plan Mode lets Claude explore the codebase and design an implementation approach before writing code. Perfect for complex tasks where you want to review the strategy first.

Plan Mode Tools

Tool Description
EnterPlanMode Start planning (read-only, no edits)
ExitPlanMode Request approval and start implementing

Planning Phases

Phase Actions
1. Explore Launch Explore agents to understand codebase
2. Design Launch Plan agents for implementation strategy
3. Review Read critical files, clarify questions
4. Write Plan Document approach in plan file
5. Approve User approves, Claude implements
โœ“
When to Use
  • New feature implementation
  • Multiple valid approaches exist
  • Architectural decisions needed
  • Multi-file changes
โœ—
When to Skip
  • Simple bug fixes
  • Single-line changes
  • User gave specific instructions
๐Ÿ’ก Triggering Plan Mode
Ask Claude to "plan this before implementing" or use EnterPlanMode tool. Claude can also proactively enter plan mode for complex tasks.
๐Ÿ“
Multi-file Editing
Work across your entire codebase

Claude Code excels at multi-file operations, using agentic search to understand your entire codebase without manual context selection. Perfect for refactors, feature implementation, and cross-cutting changes.

Multi-file Capabilities

Feature Description
Agentic Search Automatically finds relevant files without manual selection
Cross-file Refactors Rename symbols, update imports across the codebase
Parallel Instances Run multiple Claude instances on different parts of codebase
Deep Understanding Follows dependencies, understands architecture
# Refactor across multiple files > Rename the User class to Account and update all references # Implement feature touching many files > Add authentication middleware to all API routes # Analyze codebase patterns > Find all places where we handle errors inconsistently
๐Ÿš€
Best Use Cases
  • Large-scale refactoring
  • Adding cross-cutting features
  • Codebase-wide bug fixes
  • Migration tasks
๐Ÿ’ก Pro Tip
Run multiple Claude instances in parallel in different IDE panes, each working on separate parts of your codebase for maximum efficiency.
โœจ
Best Practices
Get the best results from Claude

Follow these tips to get the best results from Claude Code and maximize your productivity.

โœ“
Do This
  • Be specific about what you want
  • Provide context with @ mentions
  • Break complex tasks into steps
  • Use CLAUDE.md for project context
  • Review changes before accepting
โœ—
Avoid This
  • Vague requests like "fix it"
  • Skipping the review step
  • Ignoring context limits
  • Not using /compact in long sessions
  • Assuming Claude knows everything

Prompt Patterns

Instead of... Try...
"Fix the bug" "Fix the null pointer error in @auth.ts line 42"
"Make it faster" "Optimize the database query in @users.ts to use indexing"
"Add tests" "Add unit tests for the login function covering edge cases"
๐ŸŽฏ The Golden Rule
The more context and specificity you provide, the better Claude's response will be. Treat it like explaining to a skilled colleague who just joined your project.
๐Ÿ”„
Workflow Patterns
Combine tools for powerful workflows

Combine Tasks, Agents, Plan Mode, and Background operations to create powerful development workflows.

Development Workflow

Step Description Tools Used
1 Create GitHub Issue gh CLI
2 Plan implementation Plan Mode, Explore agents
3 Implement changes Edit tools, git
4 Open Pull Request gh CLI
5 Test (user action) TaskUpdate (wait)
6 Merge PR gh CLI
7 Wait for CI Background task
8 Release Build scripts, gh CLI
๐Ÿ’ก Skip Release For
  • Documentation changes (docs/, README)
  • Config/memory changes (.serena/, .github/)
  • Non-code changes that don't affect the binary
# Ask Claude to use the workflow "Create tasks and follow the development workflow to implement feature X" # Or with a custom skill /workflow Implement user authentication

Combining Tools

Combination Use Case
Tasks + blockedBy Sequential workflow with dependencies
Parallel Agents Explore multiple codepaths simultaneously
Background + Tasks Long builds without blocking conversation
Plan Mode + Tasks Get approval before executing workflow
Memories + Workflow Persist workflow patterns between sessions
๐Ÿ›
Troubleshooting
Common errors and solutions

Common issues and how to fix them. Run /doctor first to diagnose most problems.

Common Errors

Error Solution
Rate limit exceeded Wait a few minutes, or use /compact to reduce tokens
API key invalid Check ANTHROPIC_API_KEY env variable
Context too long Use /compact or /clear to reduce context
File not found Check file path and use Tab for autocomplete
Permission denied Check file permissions or run with sudo
MCP connection failed Check MCP server config and restart Claude
# Run diagnostics > /doctor # Clear everything and start fresh > /clear # Reduce context if hitting limits > /compact # Check your API key echo $ANTHROPIC_API_KEY
๐Ÿ†˜ Still stuck?
Use /bug to report issues to Anthropic, or check GitHub Issues for known problems.
โณ
Background Tasks
Run long operations in the background

Claude can run tasks in the background while you continue working. Great for long builds, tests, or complex operations.

# Ask Claude to run something in background > Run the full test suite in the background # Check on running tasks > /tasks # Claude will notify when done

Task Management

Command Description
/tasks List all running background tasks
Notification hook Get notified when tasks complete
๐Ÿš€
Use Cases
  • Running full test suites
  • Long builds and compilations
  • Large file processing
  • Multiple parallel operations