This guide covers professional tips for effectively using Claude Code for agentic coding. Claude Code is Anthropic's open-source AI assistant that brings the power of Claude directly into your terminal. It functions as a conversational, "agentic" command-line tool that can reason about your requests, choose tools, and execute multi-step plans to help with your development workflow.
- Getting Started
- Tip 1: Use CLAUDE.md for Persistent Context
- Tip 2: Create Custom Slash Commands
- Tip 3: Extend Claude Code with MCP Servers
- Tip 4: Leverage Context Management
- Tip 5: Use Checkpoints and Rewind
- Tip 6: Read Google Docs, Sheets with MCP
- Tip 7: Reference Files with @ Symbol
- Tip 8: Use Skills for Recurring Workflows
- Tip 9: System Troubleshooting & Configuration
- Tip 10: Auto Mode - Skip Permissions
- Tip 11: Headless & Scripting Mode
- Tip 12: Save and Resume Sessions
- Tip 13: Multi-Directory Workspace
- Tip 14: Organize Files with AI
- Tip 15: Compress Conversations with /compact
- Tip 16: Shell Commands with ! Syntax
- Tip 17: Leverage All CLI Tools
- Tip 18: Multimodal AI - Images and More
- Tip 19: Use Hooks for Automation
- Tip 20: Prompt Caching - Reduce Costs and Latency
Tip 21: /copy Command❌ NOT AVAILABLE- Tip 22: Master Keyboard Shortcuts
- Tip 23: Customize with Settings
- Tip 24: VS Code Integration
- Tip 25: GitHub Integration
- Tip 26: Use Subagents for Complex Tasks
- Tip 27: Plan Mode for Complex Problems
- Tip 28: Plugins for Extended Functionality
You can install Claude Code via multiple methods:
MacOS/Linux:
curl -fsSL https://claude.ai/install.sh | bashHomebrew (MacOS):
brew install --cask claude-codeWindows:
irm https://claude.ai/install.ps1 | iexNPM:
npm install -g @anthropic-ai/claude-codeOn first use, you'll be prompted to log in with your Anthropic account. Claude Code is available to Max, Pro, Team, and Enterprise users.
To start an interactive session, navigate to your project directory and run:
cd your-project
claudeFor non-interactive (headless) usage, use the -p flag:
claude -p "Create a React component for user login"Quick use-case: Stop repeating yourself. Provide project-specific context by creating a CLAUDE.md file in your project root. This ensures Claude always has important background knowledge.
Create a .claude folder (if not present) in your project root and add a CLAUDE.md file:
# Project Phoenix - AI Assistant Context
## Code Standards
- All TypeScript code must follow strict typing
- Use functional components with React hooks
- Prefer composition over inheritance
## Project Architecture
- Frontend: React + TypeScript + Tailwind
- Backend: Node.js + Express + PostgreSQL
- API follows REST conventions
## Key Commands
- Build: `npm run build`
- Test: `npm test`
- Lint: `npm run lint`Claude Code will automatically load this context every time you start a session in this project. This means Claude is always primed with your project's conventions, avoiding repetitive explanations.
- Place
CLAUDE.mdat your project root for project-wide context - You can also use global context at
~/.claude/CLAUDE.mdfor cross-project preferences - Keep it organized and concise - focus on what Claude needs to know most
- Use Claude to help generate your initial
CLAUDE.mdby asking: "Generate a CLAUDE.md for this project"
Quick use-case: Automate repetitive tasks with custom shortcuts. Create /test-gen to generate unit tests, or /commit to create conventional commit messages.
Custom slash commands are markdown files stored in:
- Project commands:
.claude/commands/(shared with your team) - Personal commands:
~/.claude/commands/(available across all projects)
Example: Create a code review command
Create .claude/commands/review.md:
---
description: Comprehensive code review
allowed-tools: Read, Grep, Glob, Bash(git diff:*)
model: sonnet
---
# Code Review
## Changed Files
!`git diff --name-only HEAD~1`
## Detailed Changes
!`git diff HEAD~1`
## Review Checklist
Review the changes for:
1. Code quality and readability
2. Security vulnerabilities
3. Performance implications
4. Test coverage
5. Documentation updates
Provide specific, actionable feedback organized by priority.Now you can run /review anytime to execute this workflow.
- Arguments: Use
$ARGUMENTSto pass parameters - Shell execution: Use
!git command`` to run commands and inject output - Model selection: Specify
model: haikuormodel: sonnetin frontmatter - Tool restrictions: Use
allowed-toolsto limit what Claude can do
Example with arguments:
.claude/commands/test.md:
---
description: Run tests with optional pattern
allowed-tools: Bash, Read, Edit
argument-hint: [test-pattern]
model: haiku
---
Run tests matching pattern: $ARGUMENTS
1. Detect the test framework
2. Run tests with the provided pattern
3. If tests fail, analyze and fix them
4. Re-run to verify fixesUsage: /test user-auth
- Share commands by committing them to
.claude/commands/in your repo - Use
model: haikufor fast, simple tasks (linting, commits) - Use
model: sonnetfor complex reasoning (debugging, architecture) - Ask Claude to create commands for you: "Create a /lint command that fixes ESLint issues"
Quick use-case: Connect Claude to external systems like Google Drive, Figma, Slack, or custom databases through Model Context Protocol (MCP) servers.
MCP (Model Context Protocol) is a standard that allows Claude to interface with external tools and services. You can use pre-built MCP servers or create your own.
Via CLI:
claude mcp add myserverVia configuration file:
Create or edit .mcp.json in your project root:
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"]
},
"google-drive": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-gdrive"]
}
}
}Popular MCP servers include:
- Google Drive: Access docs, sheets, and files
- GitHub: Manage issues, PRs, and code
- Slack: Send messages and read channels
- Figma: Fetch designs and components
- Puppeteer: Browser automation
- Database connectors: PostgreSQL, MySQL, etc.
Once configured, MCP tools are available as slash commands with the prefix mcp__:
# List GitHub PRs
/mcp__github__list_prs
# Review a specific PR
/mcp__github__pr_review 456
# Read a Google Doc
/mcp__google-drive__read_doc <doc-id>- Use
--mcp-debugflag when launching to troubleshoot MCP issues:claude --mcp-debug - Check
.mcp.jsoninto git to share MCP configuration with your team - List available MCP tools with
/mcpcommand - OAuth-based MCP servers can securely connect to APIs without exposing credentials
Quick use-case: Keep important facts and decisions at Claude's fingertips by managing context effectively through CLAUDE.md and project documentation.
- Use CLAUDE.md for persistent knowledge (see Tip 1)
- Reference files explicitly with @ (see Tip 7)
- Document decisions and patterns
- Keep context organized and relevant
Document key decisions:
## Architectural Decisions
### Date: 2025-01-15
Decision: Use PostgreSQL over MongoDB
Rationale: Need ACID compliance for financial dataDefine patterns:
## Common Patterns
### Error Handling
All async functions should use try-catch with proper error logging:
```typescript
try {
const result = await apiCall();
return result;
} catch (error) {
logger.error("API call failed", { error });
throw new ApplicationError("Operation failed");
}
```- Keep CLAUDE.md focused on essential information
- Use subdirectories for detailed documentation
- Reference specific docs when needed: "Check @docs/api-design.md for API patterns"
- Regularly update context as the project evolves
Quick use-case: Claude Code automatically tracks file edits as checkpoints. Use the rewind feature to undo changes and restore previous code states during your session.
Claude Code automatically creates a checkpoint for every user prompt. This allows you to:
- Rewind to any previous point in your session
- Recover code states even after accepting changes
- Choose what to rewind: conversation, code, or both
- Maintain session history across restarts (cleaned up after 30 days)
Two ways to access rewind:
- Press
Esctwice (Esc+Esc) - Use the
/rewindcommand
Both open the interactive rewind menu with three options:
1. Conversation only
- Rewind to a previous user message
- Keep all code changes
- Useful when you want to try a different approach without losing work
2. Code only
- Revert file changes to a previous checkpoint
- Keep the conversation history
- Perfect for undoing code changes that introduced bugs
3. Both code and conversation
- Restore both conversation and files to a prior point
- Complete rollback to any checkpoint in the session
- Most comprehensive recovery option
✅ Tracked:
- All file edits made during the session
- Checkpoint created for every user prompt
- Changes persist across session restarts
❌ Not tracked:
- Bash command changes (file system modifications)
- External file modifications (outside Claude Code)
- Changes from other concurrent sessions
- Experiment freely: Checkpoints let you try different approaches safely
- Quick recovery: Rewind is faster than git for session-level undo
- Combine with git: Checkpoints complement but don't replace version control
- 30-day retention: Checkpoints auto-clean after 30 days (configurable)
- Double-tap
Escfor quick access to rewind - Use "Code only" rewind to fix bugs while keeping context
- Use "Conversation only" to retry prompts with different wording
- Checkpoints are perfect for exploring multiple solutions
- For long-term history, still commit to git regularly
Note: Checkpointing is designed for quick, session-level recovery. For production code and long-term version control, always use git commits.
Quick use-case: Access Google Workspace documents directly from Claude Code by pasting links or doc IDs.
Configure Google Drive MCP in .mcp.json:
{
"mcpServers": {
"google-drive": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-gdrive"]
}
}
}Once configured, you can:
# Reference a Google Doc
"Summarize the requirements from https://docs.google.com/document/d/..."
# Read a spreadsheet
"Extract budget data from https://docs.google.com/spreadsheets/d/..."Claude will use the MCP server to fetch and read the content, subject to your Google Drive permissions.
- OAuth authentication is handled by the MCP server
- Ensure proper permissions are set on documents
- Works with Docs, Sheets, Slides, and Drive files
- Can also write back to docs if the MCP server supports it
Quick use-case: Point Claude directly to files and directories for precise context. Instead of describing code, show it: @./src/main.ts
Single file:
"Explain this code: @./src/auth.ts"Multiple files:
"Compare @./client/api.ts and @./server/routes.ts"Entire directory:
"Refactor all files in @./utils/ to use async/await"Images:
"Describe what you see in @./design/mockup.png"The @ syntax includes file contents directly in the prompt context. Claude can read:
- Source code (all languages)
- Text files (.txt, .md, etc.)
- Configuration files
- Images (PNG, JPEG, etc.)
- PDFs (text extraction)
- Be explicit: Always use
@for files you want Claude to see - Scope appropriately: Reference specific files over entire directories when possible
- Image analysis: Claude can read screenshots, diagrams, mockups, and perform OCR
- Ignore files: Claude respects
.gitignoreand.claudeignorepatterns
- Use
@for precise debugging:"Fix the bug in @./src/payment.ts at line 145" - Chain file references:
"Apply the pattern from @./patterns/auth.ts to @./src/user.ts" - Avoid referencing huge directories unnecessarily - be targeted
Quick use-case: Skills are like supercharged slash commands that Claude can invoke automatically based on context. Perfect for workflows that should run automatically.
Skills are sets of instructions and/or code that Claude can run on-demand or automatically. Unlike slash commands (which you invoke manually), Skills can be triggered by Claude when it detects the right context.
Skills are stored in .claude/skills/ as markdown files:
Example: .claude/skills/slack-notifier.md
---
description: Notify team on Slack when pushing features
trigger: after_git_push
allowed-tools: Bash, MCP(slack)
---
# Slack Notification Skill
When code is pushed to the main branch:
1. Get the commit message and changes
2. Format a concise summary
3. Post to #engineering channel on Slack
4. Include link to commit
Use professional but friendly tone.| Feature | Slash Command | Skill |
|---|---|---|
| Invocation | Manual (/command) |
Automatic or manual |
| Trigger | User types command | Context-based |
| Scope | Single task | Workflow automation |
| Best for | On-demand actions | Recurring patterns |
- Use Skills for "always do this" workflows
- Use Slash Commands for "I want to do this now" actions
- Skills can call other tools and MCP servers
- Document your Skills in CLAUDE.md so Claude knows when to use them
Quick use-case: Use Claude Code for general system administration tasks, not just coding. Fix dotfiles, diagnose errors, customize your dev environment.
Edit configuration files:
"Fix my .bashrc file - it has a PATH error"
"Optimize my .zshrc for development"
"Configure my .gitconfig with proper aliases"Diagnose system issues:
"I'm getting EACCES errors with npm install - help me fix this"
"Why is my Docker daemon not starting?"
"Debug this Python import error: [paste error]"Setup and installation:
"Install and configure PostgreSQL on macOS"
"Set up Docker with proper user permissions"
"Configure my SSH keys for GitHub"- Run Claude from your home directory for system-wide tasks
- Claude can read system logs and config files
- Always review system commands before approving them
- Use for workstation customization and environment setup
Quick use-case: Let Claude work without asking permission for every action. Similar to "YOLO mode" - fast but requires trust.
Method 1: Command flag
claude --dangerously-skip-permissionsMethod 2: Interactive toggle
Press Esc during a session to enter Auto Mode
Method 3: Specific permissions
Use /permissions command to configure which tools can run without approval:
/permissions
# Then approve specific command patterns- Claude executes file edits immediately
- Runs bash commands without confirmation
- Makes git commits and pushes
- Installs packages automatically
✅ Good use cases:
- Working on features with frequent small edits
- Running established workflows
- In a sandboxed environment
- When using hooks for validation
❌ Avoid auto mode when:
- Running destructive operations
- In production environments
- Working with sensitive data
- First time on a new codebase
- Use git: Commit frequently so you can revert
- Configure hooks: Add validation hooks that run before accepting changes
- Selective approval: Use
/permissionsto allow only safe commands - Stay alert: You can press
Escto interrupt at any time
Combine auto mode with validation hooks:
{
"hooks": {
"before_edit_applied": ["prettier --write {file}"],
"after_edit_applied": ["npm run typecheck {file}"]
}
}This ensures code quality even in auto mode.
Quick use-case: Integrate Claude Code into CI/CD pipelines, scripts, and automation by running it non-interactively.
Use the -p flag for single-shot execution:
claude -p "Run tests and fix any failures"Stream JSON for programmatic use:
claude -p "Analyze this code" --output-format stream-jsonCapture output:
result=$(claude -p "Generate API documentation")
echo "$result" > docs/api.mdGitHub Actions example:
name: AI Code Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Review PR
run: |
claude -p "Review the changes in this PR and comment on quality" \
--output-format stream-jsonPre-commit hook example:
#!/bin/bash
# .git/hooks/pre-commit
claude -p "Run linter and tests, fix any issues" \
--dangerously-skip-permissionsNightly log analysis:
# crontab entry
0 2 * * * cd /app && claude -p "Analyze yesterday's error logs and create a report"Automated refactoring:
claude -p "Update all API calls to use new error handling pattern" \
--output-format stream-json > refactor-log.json- Headless mode doesn't persist between sessions
- Use environment variables for sensitive data
- Parse JSON output for integration with other tools
- Combine with
--dangerously-skip-permissionsfor full automation
Quick use-case: Claude Code automatically saves your conversation history locally. Resume your most recent session or choose from previous conversations to continue where you left off.
Claude Code automatically saves all session history locally. This allows you to:
- Pause work and come back later
- Switch between different projects/tasks
- Preserve full conversation context and tool usage
- Maintain model settings across sessions
What gets saved:
- Full conversation history
- Tool usage and results
- Model and configuration settings
- Working directory context
Continue most recent session:
# Resume your latest conversation automatically
claude --continue
# Or use the short form
claude -cThis immediately continues your most recent session, loading the full conversation context.
Choose from previous sessions:
# Interactive session selector
claude --resume
# Navigate with arrow keys
# Press Esc to exit selectorThe --resume flag opens an interactive menu showing your recent sessions. Use arrow keys to browse and select which conversation to resume.
Sessions work seamlessly with headless mode:
# Continue previous session non-interactively
claude --continue --print "Show me what we accomplished so far"
# Short form
claude -c -p "Continue implementing the feature"Perfect for CI/CD pipelines or scripts that need context from previous runs.
Viewing session info:
Sessions are stored locally and include:
- Complete conversation transcript
- All file changes and edits
- Tool execution history
- Checkpoint state (for rewind feature)
Session persistence:
- Sessions persist across computer restarts
- Each directory can have independent session history
- CLAUDE.md context is always loaded automatically
1. Resume for continuity:
# Start your day
claude --continue
"What were we working on yesterday?"2. Document important decisions:
# Add key findings to CLAUDE.md for permanent reference
"Add this architectural decision to CLAUDE.md:
We're using Redis for caching with 1-hour TTL"3. Use with git commits:
# Commits serve as natural session boundaries
claude --continue
"Review changes since last commit and create a summary"4. Selective session resume:
# Use --resume to pick specific sessions
claude --resume
# Select "Feature: User Authentication" from 2 days ago- Use
--continuefor quick resumption of your latest work - Use
--resumewhen you need to go back to a specific conversation - Sessions work per-directory, so different projects have independent history
- Combine with
/compactto clean up long sessions while preserving key context - Use
/rewindto undo changes within a session
For information that should persist across all sessions:
# Update CLAUDE.md with permanent project knowledge
"Add to CLAUDE.md:
## Database Schema
- Users table: id, email, password_hash, created_at
- Posts table: id, user_id, title, content, published_at"CLAUDE.md provides permanent context that's loaded in every session, complementing session-specific history.
Quick use-case: Work across multiple repositories or directories simultaneously. Perfect for microservices or monorepo-like structures.
During launch:
# From any directory
claude
# Then add other directories
/add-dir ../backend
/add-dir ../frontend
/add-dir ~/common-utilsCheck workspace:
/workspace
# Shows all directories in current workspaceCross-repo changes:
"Update the API client in @../frontend/src/api.ts to match
the new endpoints in @../backend/routes/api.ts"Shared library updates:
"Apply this pattern from @~/common-utils/auth.ts across
all services in the workspace"- Add directories as needed during development
- Claude maintains awareness of all added directories
- Useful for microservices architectures
- Works well with monorepos
Quick use-case: Let Claude act as your intelligent file organizer. Sort downloads, rename screenshots descriptively, categorize project assets.
Clean up downloads:
"Organize my Downloads folder:
- Move images to Images/
- Move PDFs to Documents/
- Delete temp files
- Archive old installers"Rename files by content:
"Look at each PNG in @./screenshots/ and rename them
descriptively based on their content"Categorize project assets:
"Organize @./assets/ into subdirectories:
- icons/
- images/
- fonts/
based on file type and usage"Claude can see images and rename them intelligently:
# Before: IMG_1234.png, IMG_1235.png
# After: login-screen.png, dashboard-view.png
"For each image in this directory, view it and rename
with a descriptive name"- Always review proposed changes before approving
- Use for UI mockup organization
- Great for cleaning up screenshot folders
- Can detect duplicates by analyzing content
Quick use-case: When conversations get long, use /compact to compress the history and free up context space while preserving key information.
The /compact command compresses your conversation history by:
- Summarizing previous exchanges
- Removing redundant information
- Preserving important context and decisions
- Freeing up context window space
This is Claude Code's equivalent to Gemini CLI's /compress command.
Good times to compress:
- After long debugging sessions with lots of back-and-forth
- When context window is getting full
- Before starting a new major feature or topic
- After completing a major milestone
Example usage:
# Simply type the command
/compact
# Claude will compress the conversation history
# You can continue working with a cleaner context- Claude analyzes the entire conversation
- Creates a concise summary of key points:
- Decisions made
- Problems solved
- Code patterns established
- Important context
- Replaces the detailed history with the summary
- You can continue the conversation normally
- Key decisions: Architecture choices, patterns adopted
- Problem solutions: Bugs fixed and their solutions
- Important facts: Configuration details, requirements
- Current state: What you're working on, next steps
- Detailed back-and-forth exchanges
- Redundant questions and answers
- Exploration paths that didn't work out
- Verbose explanations that aren't needed anymore
- Compress proactively: Don't wait until you hit limits
- After milestones: Compress after completing features
- Before branching topics: Compress before switching to a new task
- Combine with CLAUDE.md: Important facts should still go in CLAUDE.md for persistence
- Git commits help: Commits serve as compression boundaries
# 1. Complete a feature
"Implement user authentication and commit"
# 2. Compress the conversation
/compact
# 3. Start the next feature with clean context
"Now let's implement the dashboard"Note: Compression is local to the current session. For truly persistent information, always update CLAUDE.md.
Quick use-case: Execute shell commands inline within slash commands and prompts using ! syntax.
In slash commands, use !command`` to run commands and inject output:
---
description: Show git status
---
# Current Status
!`git status`
!`git log --oneline -5`
What should we work on next?When Claude encounters !command``:
- Executes the command
- Captures the output
- Injects it into the prompt
- Claude sees the result before responding
Commit command:
# Create Commit
<git_diff>
!`git diff --cached`
</git_diff>
Generate a conventional commit message.Test runner:
# Test Results
!`npm test`
Analyze failures and fix them.- Use for dynamic context injection
- Perfect for git workflows
- Combine with $ARGUMENTS for flexible commands
- Shell commands run in project directory
Quick use-case: Claude can use any command-line tool installed on your system. Your entire toolbox is Claude's toolbox.
If it's in your $PATH, Claude can use it:
- Git, Docker, npm, pip
- ImageMagick, FFmpeg
- curl, jq, sed, awk
- Cloud CLIs (AWS, gcloud, etc.)
- Custom scripts and tools
Image processing:
"Convert all PNG images to WebP format using ImageMagick"Media manipulation:
"Use FFmpeg to extract audio from video.mp4"Cloud operations:
"Deploy this app to AWS using the AWS CLI"Data processing:
"Use jq to extract all email addresses from this JSON file"- Claude knows common tool syntax
- It can read
--helpoutput if needed - Use allowed-tools in slash commands to restrict access
- Powerful tools require careful approval
Quick use-case: Claude can see and understand images, not just read code. Use for UI reviews, screenshot debugging, diagram analysis.
UI/UX feedback:
"Review this mockup for accessibility: @./design/mockup.png"Screenshot debugging:
"This error appeared: @./error-screenshot.png
Help me debug it."OCR and text extraction:
"Extract all text from @./invoice.png and format as JSON"Design to code:
"Look at @./ui-design.png and generate the React component"- Images: PNG, JPEG, WebP
- Documents: PDFs (text extraction)
- Screenshots and mockups
- Diagrams and charts
- Claude can identify UI elements in screenshots
- Useful for organizing photos by content
- Can read text from images (OCR)
- Combine with file organization for smart photo management
Quick use-case: Hooks are shell commands that run automatically at specific points in Claude's lifecycle. Use them for formatting, validation, and quality checks.
Claude Code supports the following hooks:
- PreToolUse - Runs before any tool is executed
- PostToolUse - Runs after any tool completes
- UserPromptSubmit - Runs when user submits a prompt
- SessionStart - Runs when a session begins
- SessionEnd - Runs when a session ends
- Stop - Runs when user stops Claude
- SubagentStop - Runs when a subagent stops
- PreCompact - Runs before conversation compaction
- PermissionRequest - Runs when permissions are requested
- Notification - Runs when notifications are sent
Via settings file:
Edit .claude/settings.json or ~/.claude/settings.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "prettier --write {file}"
},
{
"type": "command",
"command": "eslint --fix {file}"
}
]
}
],
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "git fetch"
}
]
}
],
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "git status"
}
]
}
]
}
}Each hook has:
- matcher (optional): Regex pattern to match tool names (e.g.,
"Write|Edit") - hooks: Array of hook configurations
- type: Usually
"command"for shell commands - command: The shell command to execute
- type: Usually
Code formatting after file edits:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "prettier --write {file}"
}
]
}
]
}
}Type checking after edits:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "tsc --noEmit {file}"
}
]
}
]
}
}Linting before tool execution:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "eslint {file}"
}
]
}
]
}
}Session management:
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "echo 'Starting Claude Code session'"
}
]
}
],
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "git status"
}
]
}
]
}
}Available placeholders in hook commands:
{file}- The file path for file-related tools (Write, Edit, etc.)- Other tool-specific context may be available
- Hooks ensure code quality in auto mode
- Use matchers to target specific tools (Write, Edit, Bash, etc.)
- Test hooks manually before enabling
- Share hooks via git by committing
.claude/settings.json - Hooks can chain multiple commands in sequence
- Use PreToolUse for validation, PostToolUse for cleanup/formatting
Quick use-case: When using Claude Code with AWS Bedrock as your backend, prompt caching reduces costs by up to 90% and improves latency when you reuse large contexts like codebases, documentation, or conversation history.
Prompt caching is ONLY available when using AWS Bedrock as the backend for Claude Code. This feature is:
- ❌ NOT available with the default Anthropic API
- ✅ AVAILABLE when configured to use AWS Bedrock
- Requires AWS account and Bedrock setup
Learn more:
Prompt caching allows Claude to reuse previously processed content (like your codebase, system instructions, or conversation history) instead of reprocessing it with every request. This significantly reduces:
- Cost: Cache hits cost only 10% of normal input token prices (up to 90% savings)
- Latency: Cached content processes much faster, reducing latency by up to 85%
To use prompt caching with Claude Code, you need:
- AWS Account with Bedrock access
- AWS Bedrock Configuration in Claude Code
- Supported Claude models (Opus, Sonnet, Haiku via Bedrock)
When configured with AWS Bedrock, Claude Code automatically caches:
- System instructions and prompts
- Large file contexts you reference with
@ - Conversation history in extended sessions
- Tool definitions and MCP server descriptions
- CLAUDE.md and persistent context
The cache behavior depends on AWS Bedrock's configuration and is automatically managed.
When you use Claude Code with AWS Bedrock configured, caching works behind the scenes:
# First request - creates cache (with AWS Bedrock backend)
claude -p "Analyze @./large-codebase/"
# Processes all files, writes to cache
# Follow-up requests - uses cache
"Now optimize the authentication module"
# Reads codebase from cache (90% cost reduction)Note: Caching behavior depends on your AWS Bedrock configuration and region.
Best for:
- 📚 Large codebases: Entire project contexts stay cached
- 📖 Documentation: Long docs, API references, specifications
- 💬 Extended conversations: Chat history across multiple turns
- 🔧 Tool definitions: MCP servers with many tools
- 📝 System prompts: Complex instructions and examples
Example scenarios:
# Working on a large codebase
claude
"Review the entire @./src/ directory for security issues"
# (Caches the entire src directory)
"Now check for performance bottlenecks"
# (Reuses cached src directory - 90% cheaper, faster response)
"Fix the issues you found"
# (Still using cache if within 5 minutes)While Claude Code handles caching automatically, when using the API directly you can track:
cache_read_input_tokens: Tokens retrieved from cache (cheap)cache_creation_input_tokens: Tokens written to cache (25% premium)input_tokens: Regular tokens after cache breakpoint
Example API response:
{
"usage": {
"cache_read_input_tokens": 188086, // Read from cache
"cache_creation_input_tokens": 0, // Nothing new cached
"input_tokens": 21 // New user message only
}
}When using Claude Code with AWS Bedrock, caching is optimized to maximize cache hits:
- Stable content first: CLAUDE.md, tool definitions load first
- File references cached: When you use
@./file, it's cached by Bedrock - Conversation history: Multi-turn chats cache previous context
- Automatic invalidation: Cache updates when files change
Note: Specific caching behavior may vary based on your AWS Bedrock configuration.
The cache is invalidated when:
- ✘ Tool definitions change (adding/removing MCP servers)
- ✘ System prompt changes (modifying CLAUDE.md)
- ✘ Referenced files change (editing files you've
@referenced) - ✓ New user messages (don't invalidate - just add to context)
Content must meet minimum token counts to be cached:
- 1024 tokens for Opus and Sonnet models
- 4096 tokens for Haiku 4.5
Smaller contexts won't benefit from caching.
5-minute cache (default):
- Free refreshes when accessed
- Perfect for active development sessions
- Best for rapid back-and-forth coding
1-hour cache (premium):
- 2x the cache write cost
- Best for less frequent follow-ups (5-60 minute gaps)
- Useful for long-running agentic tasks
- Helps with rate limit optimization
-
Keep stable content consistent:
- Don't modify CLAUDE.md mid-session unnecessarily
- Reference the same large files across requests
-
Structure requests efficiently:
# Good - cache the whole codebase once "Review @./src/ for issues" "Fix the authentication bugs" "Add tests for the fixes" # Less efficient - different files each time "Review @./src/auth.ts" "Review @./src/api.ts" "Review @./src/utils.ts"
-
Work in focused sessions:
- Cache lasts 5 minutes, so stay active
- Batch related questions together
- Let cache refresh by staying engaged
-
Use large contexts fearlessly:
- Don't hesitate to reference entire directories
- Include full documentation
- Load comprehensive examples
-
Leverage long conversations:
- Multi-turn debugging sessions benefit most
- Each turn reuses previous context from cache
- Cost per message drops dramatically
With Skills:
# Skill that references large context
---
## description: Code review with caching
Review all files in @./src/ directory.
# First run caches ./src/
# Subsequent skill runs use cacheWith Subagents:
- Each subagent can benefit from cached context
- Shared context is cached once, used by all agents
With VS Code Integration:
- Open files are automatically included in context
- Context is cached for subsequent requests
High impact scenarios:
- 🏗️ Working with codebases >100k tokens
- 📚 Analyzing multiple documents repeatedly
- 🔄 Iterative debugging sessions
- 🤖 Agentic workflows with multiple tool calls
- 💬 Long conversations with extensive context
Lower impact scenarios:
- Quick one-off questions
- Small file edits
- First-time analysis of new code
- Infrequent API calls (>5 min apart)
# Session 1: Analyze large codebase
$ claude
> "Analyze the entire @./src/ directory architecture"
# Cost: $1.50 for 50k tokens (cache write)
# Response time: 3 seconds
> "What security vulnerabilities exist?"
# Cost: $0.15 for 50k cached + 0.05 for new
# Response time: 1 second (cache hit!)
> "Fix the SQL injection issues"
# Cost: $0.15 for 50k cached + 0.05 for new
# Response time: 1 second (cache hit!)
# Total: ~$1.85 instead of $4.50 without caching
# Time saved: 4+ seconds per requestPrompt caching with AWS Bedrock and Claude Code:
⚠️ Requires AWS Bedrock - not available with default Anthropic API- ✅ Saves up to 90% on costs for repeated context
- ✅ Reduces latency by up to 85%
- ✅ Perfect for large codebase work
- ✅ Enables fearless use of comprehensive context
To get started: Configure Claude Code to use AWS Bedrock as your backend. Once configured, caching works automatically based on your Bedrock settings.
Status: This feature from Gemini CLI is not currently available in Claude Code.
Gemini equivalent: /copy to copy last response to clipboard.
Claude Code alternative:
- Select and copy text from terminal
- Redirect output to files:
claude -p "..." > output.txt - Use your terminal's copy functionality
Want this feature? There's an active GitHub issue requesting this functionality:
- Feature Request: Add /copy command
- Feel free to upvote or add your use case to help prioritize this feature!
Quick use-case: Navigate Claude Code efficiently with keyboard shortcuts.
| Shortcut | Action |
|---|---|
Esc |
Toggle auto mode / interrupt operation |
Esc + Esc |
Open rewind menu (see Tip 5) |
Shift+Tab |
Toggle plan mode (extended thinking) |
Tab |
Toggle extended thinking |
Ctrl+C |
Cancel current operation |
Ctrl+D |
Exit Claude Code |
Ctrl+L |
Clear screen |
Ctrl+V / Alt+V |
Paste image from clipboard |
Ctrl+R |
Search command history |
/ |
Show available slash commands |
@ |
Reference files and directories |
Enter multiline prompts using any of these methods:
\+Enter- Backslash to continue on next lineShift+Enter- Continue without submittingOption+Enter- macOS alternativeCtrl+J- Another alternative- Direct paste - Paste multiline text directly
- Double-tap
Escfor quick access to rewind feature - Use
Shift+Tabto activate plan mode for complex problems Ctrl+Lclears screen clutter without losing session- Paste images directly with
Ctrl+Vfor multimodal analysis Ctrl+Rlets you search and reuse previous commands
Quick use-case: Tailor Claude Code's behavior through the settings file for consistent workflows.
- Project settings:
.claude/settings.json - Global settings:
~/.claude/settings.json
Project settings override global settings.
Example settings.json:
{
"default_model": "sonnet",
"auto_commit": false,
"hooks": {
"before_edit_applied": ["prettier --write {file}"],
"after_edit_applied": ["npm run typecheck {file}"]
},
"allowed_tools": ["Read", "Edit", "Bash"],
"mcp_servers": {
"github": {
"enabled": true
}
}
}{
"default_model": "sonnet", // or "opus" or "haiku"
"model_preferences": {
"complex_tasks": "opus",
"simple_tasks": "haiku"
}
}- Commit
.claude/settings.jsonto share team settings - Use global settings for personal preferences
- Override specific settings per project
- Ask Claude to help configure settings
Quick use-case: Use Claude Code directly in VS Code for seamless IDE integration with context awareness.
Install VS Code extension:
- Search for "Claude Code" in VS Code marketplace
- Install the official Anthropic extension
- Claude Code will automatically detect VS Code integration
Context awareness:
- Claude sees your open files
- Knows your cursor position
- Understands your workspace structure
Diff view:
- Proposed changes open in VS Code's diff editor
- Review changes with familiar interface
- Accept or reject inline
Command palette:
- Access Claude Code via
Cmd+Shift+P(Mac) orCtrl+Shift+P(Windows/Linux) - Run commands without leaving the editor
From integrated terminal:
# Run Claude Code in VS Code's terminal
claudeSide-by-side workflow:
- Keep Claude Code terminal open
- View code changes in main editor
- Use diff view for reviews
- Claude automatically uses open files as context
- Great for Jupyter notebook workflows
- Works with VS Code's git integration
- Use
@to explicitly reference files not in your workspace
Quick use-case: Automate GitHub workflows - create PRs, review code, manage issues, all through Claude.
Add to .mcp.json:
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"]
}
}
}Create pull request:
"Create a PR for these changes with a descriptive title and summary"
# Claude understands "pr" shorthandReview PR:
"Review PR #123 and provide feedback"Fix PR comments:
"Fix all comments on my PR and push updates"Manage issues:
"Create an issue for this bug with reproduction steps"Claude can use gh CLI if installed:
"Use gh to list my open PRs"
"Close issue #45 with gh"Install GitHub app:
/install-github-appThis enables automatic PR reviews by Claude on every pull request.
Customize review prompt:
Edit claude-code-review.yml:
prompt: |
Review this PR focusing on:
- Security vulnerabilities
- Logic errors
- Performance issues
Be concise. Only comment on genuine issues.- Claude generates conventional commit messages automatically
- Use
prshorthand for pull requests - GitHub Actions can run Claude Code in CI
- Customize review prompts to avoid over-commenting
Quick use-case: Subagents are specialized Claude instances with specific roles and tools. Use them for modular, complex workflows.
Subagents are defined Claude instances with:
- Specific expertise/role
- Limited tool access
- Focused context
- Custom prompts
Via CLI flag:
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer",
"prompt": "You are a senior code reviewer. Focus on security and best practices.",
"tools": ["Read", "Grep", "Glob"],
"model": "sonnet"
},
"debugger": {
"description": "Debugging specialist",
"prompt": "Expert at finding and fixing bugs",
"tools": ["Read", "Edit", "Bash"],
"model": "opus"
}
}'Via configuration file:
.claude/agents/reviewer.md:
---
description: Code quality expert
allowed-tools: Read, Grep, Bash(git diff:*)
model: sonnet
---
You are a senior software engineer focused on code quality.
Review code for:
- Security vulnerabilities
- Performance issues
- Code smells
- Best practicesDelegate to subagents:
"Have the code-reviewer check this file, then the debugger fix any issues"Subagents in workflows:
.claude/commands/feature-complete.md:
---
description: Complete feature workflow
---
1. Review code with code-reviewer agent
2. Fix issues with debugger agent
3. Generate tests with test-generator agent
4. Create PR with summary- Use subagents for separation of concerns
- Limit tool access per agent for safety
- Combine multiple agents in workflows
- Useful for complex multi-step tasks
Quick use-case: For complex features or refactors, use Plan Mode to have Claude create a comprehensive strategy before coding.
Plan Mode activates Claude's extended thinking capabilities to:
- Analyze the problem deeply
- Create detailed implementation plans
- Break down complex tasks
- Identify edge cases
Enable during session:
Press Shift+Tab to toggle plan mode on/off, or ask explicitly:
"Use plan mode to design a solution for [complex problem]"Workflow with Plan Mode:
- Research: "Research the best approach for implementing OAuth2"
- Plan: "Create a detailed plan for the implementation"
- Review: Review the plan, save it if good
- Implement: "Implement the plan step by step"
- Verify: "Verify the implementation against the plan"
# Step 1: Research
"Research authentication patterns for SaaS apps"
# Step 2: Plan
"Create a detailed implementation plan.
Save it as @./docs/auth-plan.md"
# Step 3: Implement
"Implement the plan from @./docs/auth-plan.md
Verify each step against requirements"
# Step 4: Test
"Write comprehensive tests for the implementation"
# Step 5: PR
"Create a PR with detailed changelog"- Press
Shift+Tabto quickly toggle plan mode during your session - Use plan mode for unfamiliar problems
- Save plans as documentation
- Plans help with code review
- Can reset to plan if implementation goes wrong
- Especially useful for refactoring large codebases
Quick use-case: Plugins are packaged collections of slash commands, subagents, and configurations that extend Claude Code's capabilities.
Via plugin marketplace:
/plugin marketplace add <url>
/plugin install <plugin-name>Example plugins:
claude-code-essentials- Core development workflowsfull-stack-development- Frontend and backend toolssecurity-hardening- Security scanning and auditingdata-ml-pipeline- Data science workflows
Development workflows:
- Feature development pipelines
- Testing frameworks
- Deployment automation
Code quality:
- Security scanners
- Performance analyzers
- Documentation generators
Infrastructure:
- Docker optimization
- Kubernetes manifests
- CI/CD pipelines
Plugins are structured directories with:
my-plugin/
├── commands/ # Slash commands
├── agents/ # Agent definitions
├── skills/ # Automated workflows
└── plugin.json # Plugin metadata
Example plugin.json:
{
"name": "my-dev-workflow",
"version": "1.0.0",
"description": "Custom development workflow",
"commands": ["commit", "pr", "deploy"],
"subagents": ["reviewer", "tester"]
}- Browse community plugins for inspiration
- Share plugins with your team
- Plugins provide turnkey workflows
- Combine multiple plugins for comprehensive tooling
Claude Code is a powerful agentic coding assistant that becomes even more capable when you master these techniques:
- Context: Use CLAUDE.md and @ references
- Automation: Create slash commands and skills
- Integration: Connect MCP servers for external tools
- Validation: Set up hooks for code quality
- Collaboration: Share configuration via git
- Install Claude Code
- Create CLAUDE.md for your project
- Set up useful slash commands
- Configure hooks for code quality
- Add MCP servers for tools you use
- Try VS Code integration
- Experiment with subagents for complex tasks
- Learn Esc key for reviewing changes
- Use /compact for long sessions
- Work with large codebases to benefit from automatic prompt caching
- Official Claude Code Documentation
- Claude Code GitHub
- Community Plugins
- MCP Documentation
- Claude Code Best Practices (Anthropic)
Have additional tips? Share them with the community:
- Check out Anthropic on GitHub
- Contribute to the awesome-claude-code repository
- Share your slash commands and configurations
This guide was adapted from the excellent Gemini CLI tips by Addy Osmani and customized for Claude Code with accurate feature mapping and Claude-specific best practices.