Skip to main content

CLAUDE CODECHEATSHEET

Detailed Claude Code usage reference with copy-paste examples, configuration templates, and workflow automation guides

Getting Started

Install via npm

Install Claude Code globally using npm

npm install -g @anthropic-ai/claude-code

Install via curl

Alternative installation method using curl

curl -sL https://install.anthropic.com | sh

Update to Latest

Keep Claude Code up to date

claude update

Keyboard Shortcuts

!Bash mode prefix
@Mention files/folders
\Line break (backslash + Enter)
EscInterrupt Claude
Ctrl+RFull output/context
Ctrl+VPaste image
Esc+EscHistory navigation
Shift+TabAuto-accept ("yolo mode")
Shift+Tab+TabPlan mode
Cmd+Esc / Ctrl+EscQuick launch in IDEs
Cmd+Option+K / Alt+Ctrl+KInsert file references

Configuration

📁 Settings File Locations (Priority Order)

1. Enterprise: /etc/claude-code/managed-settings.json (highest priority)
2. Project Local: .claude/settings.local.json (personal, git-ignored)
3. Project Shared: .claude/settings.json (team settings)
4. User Global: ~/.claude/settings.json (personal defaults)

View all settings

List current configuration

claude config list

Get setting value

Check specific setting

claude config get <key>

Set configuration

Change a setting value

claude config set <key> <value>

Add to list setting

Push to arrays like permissions

claude config add <key> <value>

Remove from list

Remove from array settings

claude config remove <key> <value>

⚙️ Most Useful Settings

Theme Settings

claude config set -g theme dark

Disable Auto-updates

claude config set -g autoUpdates false

Enable Verbose Output

claude config set -g verbose true

Set Default Model

Choose your preferred AI model

Opus 4.1 (most capable):
claude config set model claude-opus-4-1-20250805
Sonnet 4 (balanced):
claude config set model claude-sonnet-4-20250514
Haiku 3.5 (fastest):
claude config set model claude-3-5-haiku-20241022

Disable Co-authored By in Git

claude config set includeCoAuthoredBy false

Set Model via Environment

ZSH:
echo 'export ANTHROPIC_MODEL="claude-opus-4-1-20250805"' >> ~/.zshrc
Bash:
echo 'export ANTHROPIC_MODEL="claude-opus-4-1-20250805"' >> ~/.bashrc

Slash Commands - Interactive Session Control

⚡ Interactive Session Commands

Control Claude's behavior during interactive sessions. Type commands directly in the Claude Code chat interface.

📋 Built-in Commands

/add-dirAdd additional working directories
/agentsManage custom AI subagents for specialized tasks
/bugReport bugs (sends conversation to Anthropic)
/clearClear conversation history
/compact [instructions]Compact conversation with optional focus instructions
/configView/modify configuration
/costShow token usage statistics
/doctorCheck Claude Code installation health
/helpGet usage help
/initInitialize project with CLAUDE.md guide
/loginSwitch Anthropic accounts
/logoutSign out from your Anthropic account
/mcpManage MCP server connections and OAuth authentication
/memoryEdit CLAUDE.md memory files
/modelSelect or change the AI model
/permissionsView or update permissions
/pr_commentsView pull request comments
/reviewRequest code review
/statusView account and system statuses
/terminal-setupInstall Shift+Enter key binding (iTerm2/VSCode)
/vimEnter vim mode for alternating insert/command modes

🎯 Custom Slash Command Templates

Basic Project Command

Create a simple project-specific command

📁 Save as: .claude/commands/optimize.md
Analyze this code for performance issues and suggest optimizations:

Personal Command

Create a user-wide command available in all projects

📁 Save as: ~/.claude/commands/security-review.md
Review this code for security vulnerabilities:

Command with Arguments

Use $ARGUMENTS placeholder for dynamic values

📁 Save as: .claude/commands/fix-issue.md
Fix issue #$ARGUMENTS following our coding standards

Git Commit Command

Advanced command with bash execution and file references

📁 Save as: .claude/commands/commit.md
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
argument-hint: [message]
description: Create a git commit
---

## Context

- Current git status: !`git status`
- Current git diff: !`git diff HEAD`
- Current branch: !`git branch --show-current`
- Recent commits: !`git log --oneline -10`

## Your task

Based on the above changes, create a single git commit.

💡 Usage Tips

Project commands: Store in .claude/commands/ (shared with team)
Personal commands: Store in ~/.claude/commands/ (available across all projects)
Arguments: Use $ARGUMENTS placeholder for dynamic values
Bash execution: Use !`command` to run commands before processing
File references: Use @filename to include file contents
MCP commands: Format: /mcp__server__prompt_name

Hooks - Automation & Control

⚠️ Security Warning

Hooks execute shell commands automatically with your credentials. Always review hook code before adding. Malicious hooks can damage your system or exfiltrate data.

Use hooks to automate formatting, logging, notifications, and custom permissions instead of relying on Claude to remember these tasks.

📋 Hook Events

PreToolUseRuns before tool calls (can block them)
PostToolUseRuns after tool calls complete
UserPromptSubmitRuns when user submits a prompt, before Claude processes it
NotificationRuns when Claude Code sends notifications
StopRuns when Claude Code finishes responding
SubagentStopRuns when subagent tasks complete
PreCompactRuns before compact operation
SessionStartRuns when Claude Code starts/resumes session
SessionEndRuns when Claude Code session ends

🛠️ Hook Management Commands

/hooksOpen hooks configuration interface
claude --debugRun with debug output to see hook execution
mkdir -p .claude/hooksCreate project hooks directory
chmod +x .claude/hooks/script.shMake hook script executable

🎯 Ready-to-Use Hook Examples

Auto Format Code

Run prettier on edited files

Event: PostToolUseMatcher: Edit|Write
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write $FILE_PATH"
          }
        ]
      }
    ]
  }
}

Log Activity

Keep a log of all Claude sessions

Event: Stop
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "echo \"$(date): $CONVERSATION_SUMMARY\" >> ~/.claude/activity.log"
          }
        ]
      }
    ]
  }
}

🏗️ Hook Structure & Tips

Settings location: ~/.claude/settings.json (user) or .claude/settings.json (project)
Matchers: Match tool names (e.g., Bash, Edit|Write, *)
Project scripts: Use $CLAUDE_PROJECT_DIR for relative paths
Exit codes: 0=success, 2=block & show to Claude, other=error
JSON input: Hooks receive session data via stdin (use jq to parse)
Debugging: Use claude --debug to see hook execution details

MCP Servers & Extensions

🔌 Model Context Protocol (MCP)

Extend Claude Code with external tools and integrations. MCP servers provide additional capabilities like browser automation, database access, and API integrations.

📋 MCP Management Commands

claude mcp add <name> <command> [args...]Add MCP server with command
claude mcp add --transport sse <name> <url>Add SSE transport MCP server
claude mcp add --transport http <name> <url>Add HTTP transport MCP server
claude mcp listList installed MCP servers
claude mcp remove <name>Remove MCP server

⚡ Popular MCP Integrations

Context7

Documentation library access

claude mcp add --transport http context7 https://mcp.context7.com/mcp

Puppeteer

Browser automation

claude mcp add puppeteer -s user -- npx -y @modelcontextprotocol/server-puppeteer

Playwright

Advanced browser automation

claude mcp add playwright npx @playwright/mcp@latest

Linear

Project/issue management

claude mcp add linear -s user -- npx -y mcp-remote https://mcp.linear.app/sse

Sentry

Error tracking and monitoring

claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

Supabase

Database operations

claude mcp add supabase -s local -e SUPABASE_ACCESS_TOKEN=your_token -- npx -y @supabase/mcp-server-supabase@latest

Digital Ocean

Cloud hosting management

claude mcp add digitalocean-mcp-local -e DIGITALOCEAN_API_TOKEN=YOUR_TOKEN -- npx "@digitalocean/mcp"

Git Worktrees - Parallel Development

🚀 Why Use Git Worktrees with Claude Code?

  • No Context Loss: Each Claude session keeps full project understanding
  • Parallel Work: Handle hotfixes while continuing feature development
  • Safe Experiments: Test risky changes in complete isolation
  • Model Comparison: Run different AI models on identical tasks
  • Zero Switching Cost: No more git stash, checkout, restart cycle

📋 Essential Worktree Commands

git worktree add <path> <branch>Create worktree with existing branch
git worktree add <path> -b <branch> <start-point>Create worktree with new branch
git worktree listList all worktrees and their branches
git worktree remove <path>Remove a worktree directory
git worktree pruneClean up worktree references
git worktree move <worktree> <new-path>Move worktree to new location

💡 Powerful Workflow Examples

Parallel Feature Development

Work on multiple features simultaneously

git worktree add ../myapp-auth -b feature/auth main
git worktree add ../myapp-api -b feature/api main
cd ../myapp-auth && claude
cd ../myapp-api && claude

Hotfix While Developing

Handle urgent fixes without losing context

git worktree add ../myapp-hotfix -b hotfix/critical main
cd ../myapp-hotfix
claude "fix the critical bug"
# Original work continues in main directory

Safe Experiment Testing

Test risky changes in isolation

git worktree add ../myapp-experiment -b experiment/refactor main
cd ../myapp-experiment
claude "refactor the entire auth system"
# If it fails, just delete the directory

Model Comparison

Compare different AI implementations

git worktree add ../ml-sonnet -b experiment/sonnet main
git worktree add ../ml-opus -b experiment/opus main
cd ../ml-sonnet && claude --model sonnet
cd ../ml-opus && claude --model opus

Code Review Preparation

Polish code without affecting main work

git worktree add ../myapp-review -b review/cleanup feature-branch
cd ../myapp-review
claude "add docs, tests, and clean up code style"
git merge review/cleanup

Subagents - Specialized AI Assistants

🤖 Why Use Subagents?

  • Context Preservation: Each subagent has separate context from main conversation
  • Specialized Expertise: Fine-tuned prompts for specific domains and tasks
  • Reusable Workflows: Share subagents across projects and with your team
  • Tool Control: Grant specific tool access per subagent for security
  • Automatic Delegation: Claude proactively uses appropriate subagents

📁 Subagent Locations

Project subagents: .claude/agents/ (highest priority, team shared)
User subagents: ~/.claude/agents/ (personal, all projects)
File format: Markdown with YAML frontmatter

📋 Essential Subagent Commands

/agentsOpen subagents management interface
claude "Use the [name] subagent to..."Explicitly invoke a specific subagent
mkdir -p .claude/agentsCreate project subagents directory
mkdir -p ~/.claude/agentsCreate user subagents directory

🎯 Ready-to-Use Subagent Templates

Code Reviewer

Expert code review after writing/modifying code

📁 Save as: .claude/agents/code-reviewer.md
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
---

You are a senior code reviewer ensuring high standards of code quality and security.

When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately

Review checklist:
- Code is simple and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed

Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)

Include specific examples of how to fix issues.

Debugger

Debugging specialist for errors and test failures

📁 Save as: .claude/agents/debugger.md
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---

You are an expert debugger specializing in root cause analysis.

When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works

Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states

For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations

Focus on fixing the underlying issue, not just symptoms.

💡 Usage Tips

Automatic invocation: Include "proactively" or "MUST BE USED" in descriptions
Explicit invocation: "Use the code-reviewer subagent to check my code"
Chaining: "Use debugger then optimizer subagents"
Tool limitation: Only grant necessary tools for security and focus
Team sharing: Check project subagents into version control

📝 Subagent File Format

---
name: your-subagent-name
description: When this subagent should be invoked
tools: Read, Edit, Bash  # Optional - inherits all if omitted
---

Your subagent's system prompt goes here.
Include specific instructions, examples, and constraints.

Define the subagent's role, capabilities, and approach
to solving problems within its domain.

Permissions & Security

🔒 Ready-to-Use Permission Templates

Copy complete settings.json configurations for different security levels. Save to .claude/settings.json in your project.

Basic Security

Block sensitive files, allow common dev commands

💡 Good starting point for most projects
{
  "permissions": {
    "allow": [
      "Bash(npm run *)",
      "Bash(git status)",
      "Bash(git diff)",
      "Bash(git add *)",
      "Bash(git commit *)"
    ],
    "ask": [
      "Bash(git push:*)",
      "Bash(npm install *)"
    ],
    "deny": [
      "Read(./.env*)",
      "Read(./secrets/**)",
      "Read(./**/credentials*)",
      "Bash(rm -rf:*)",
      "Bash(curl:*)"
    ]
  }
}

Strict Security

Maximum security for sensitive projects

💡 For production systems or sensitive codebases
{
  "permissions": {
    "ask": [
      "Bash(*)",
      "Write(*)",
      "Edit(*)"
    ],
    "deny": [
      "Read(./.env*)",
      "Read(./secrets/**)",
      "Read(./config/**)",
      "Read(./**/credentials*)",
      "Read(./**/*.key)",
      "Read(./**/*.pem)",
      "WebFetch",
      "Bash(curl:*)",
      "Bash(wget:*)",
      "Bash(ssh:*)"
    ]
  }
}

Printable Cheatsheet

Claude Code Cheatsheet - Printable version with keyboard shortcuts, commands, and configurations

Printable Version

Special version for printing or keeping as a desktop reference. Contains all essential keyboard shortcuts, commands, configurations, and file locations in a compact format.