All Cheatsheets
Claude Code Cheatsheet
Cheatsheet

Claude Code Cheatsheet

Complete reference guide for Claude Code CLI with commands, keyboard shortcuts, configuration, and best practices

DevBuild StudioUpdated January 2024

Quick Reference: Master Claude Code with this comprehensive cheatsheet. Includes installation, commands, shortcuts, and advanced features. Bookmark for instant access!

Getting Started

Claude Code is Anthropic's official CLI tool that brings Claude AI directly into your development workflow. It's your intelligent pair programming partner, right in your terminal.

Installation

bash
1# Install with npm (recommended)
2npm install -g @anthropic-ai/claude-code
3
4# Install with homebrew (macOS/Linux)
5brew install claude-code
6
7# Install with pipx (Python)
8pipx install claude-code

Quick Start

bash
1# Set your API key
2export ANTHROPIC_API_KEY="your-api-key-here"
3
4# Start Claude Code in current directory
5claude
6
7# Start in a specific directory
8claude /path/to/project
9
10# Start with a specific task
11claude "Add login functionality"

Prerequisites

  • Node.js 20.9.0+ or Python 3.10+
  • Anthropic API key from console.anthropic.com
  • Git (for version control features)
  • 200MB free disk space

Keyboard Shortcuts

Essential Shortcuts

ShortcutPurposeDescription
Esc EscCancelCancel current operation or exit prompt
Ctrl+CInterruptStop current AI response
Ctrl+DExitClose Claude Code session
Ctrl+RRetryRetry last request with same prompt
Ctrl+LClearClear the terminal screen
/ HistoryNavigate through command history

Editor Shortcuts

ShortcutPurposeDescription
Ctrl+EOpen EditorOpen multi-line input editor
Ctrl+XSave & SendSave editor and send message
Ctrl+KCancel EditCancel editor without sending
TabAutocompleteAutocomplete file paths and commands
ShortcutPurposeDescription
Ctrl+PPreviousGo to previous conversation turn
Ctrl+NNextGo to next conversation turn
Ctrl+HomeFirstJump to first message
Ctrl+EndLastJump to last message

Configuration

Global Settings

bash
1# View current configuration
2claude config list
3
4# Set configuration value
5claude config set <key> <value>
6
7# Reset to defaults
8claude config reset

Core Configuration Options

SettingDefaultDescription
modelclaude-sonnet-4-5AI model to use
auto_approvefalseAuto-approve file operations
max_tokens8192Max tokens per response
temperature1.0Response creativity (0.0-1.0)
themeautoUI theme: light, dark, auto

Configuration File

yaml
1# 📁 ~/.claude/config.yaml
2
3model: claude-sonnet-4-5
4auto_approve: false
5max_tokens: 8192
6temperature: 1.0
7theme: auto
8
9# Editor settings
10editor:
11  default: vscode
12  open_on_edit: true
13
14# File handling
15files:
16  max_size: 10MB
17  exclude_patterns:
18    - node_modules/
19    - .git/
20    - dist/
21    - build/
22
23# Git integration
24git:
25  auto_commit: false
26  commit_prefix: "chore:"
27
28# Advanced
29advanced:
30  enable_memory: true
31  cache_responses: true
32  verbose_logging: false

Slash Commands

File Operations

CommandDescriptionExample
/read <file>Read file contents/read src/App.tsx
/edit <file>Edit existing file/edit package.json
/create <file>Create new file/create components/Button.tsx
/delete <file>Delete file (with confirmation)/delete old-config.js
/glob <pattern>Find files by pattern/glob **/*.test.ts
CommandDescriptionExample
/cd <dir>Change directory/cd src/components
/ls [path]List directory contents/ls src/
/pwdPrint working directory/pwd
/tree [path]Show directory tree/tree src/

Git Commands

CommandDescriptionExample
/git statusShow git status/git status
/git diffShow changes/git diff
/commitCreate commit with AI message/commit
/git logShow commit history/git log --oneline -10

Session Management

CommandDescriptionExample
/checkpointSave conversation state/checkpoint feature-complete
/restoreRestore checkpoint/restore feature-complete
/clearClear conversation history/clear
/resetReset to initial state/reset
/memoryView/manage memory/memory show

Utility Commands

CommandDescriptionExample
/helpShow help menu/help
/settingsOpen settings/settings
/costShow API usage/cost/cost
/exportExport conversation/export chat.md
/exitExit Claude Code/exit

Checkpointing System

Checkpoints allow you to save and restore conversation state, perfect for experimenting or working on multiple features.

Creating Checkpoints

bash
1# Create a checkpoint with name
2/checkpoint my-checkpoint-name
3
4# Create with description
5/checkpoint "Before refactoring auth system"
6
7# Quick checkpoint (auto-named)
8/checkpoint

Restoring Checkpoints

bash
1# Restore specific checkpoint
2/restore my-checkpoint-name
3
4# List all checkpoints
5/checkpoint list
6
7# Delete checkpoint
8/checkpoint delete my-checkpoint-name

Checkpoint Best Practices

Pro Tip: Create checkpoints before major refactorings or risky operations. You can always roll back!

  1. Before Refactoring: cd /checkpoint "Before auth refactor"
  2. After Feature Complete: /checkpoint "Feature X complete - tests passing"
  3. Before Experiments: /checkpoint "Baseline before trying new approach"

Memory System

Claude Code has persistent memory that learns your preferences and project patterns.

Memory Commands

bash
1# View current memory
2/memory show
3
4# Add to memory
5/memory add "Always use functional components in React"
6
7# Clear memory
8/memory clear
9
10# Update memory
11/memory update "Prefer arrow functions"

What Memory Stores

  • Code Style: Preferred patterns, naming conventions
  • Project Context: Architecture decisions, tech stack
  • User Preferences: Editor choice, formatting preferences
  • Common Patterns: Frequently used implementations

Memory is stored locally in ~/.claude/memory/ and persists across sessions.


Common Workflows

1. Creating a New Feature

bash
1# Start with context
2claude "I need to add user authentication"
3
4# Let Claude analyze codebase
5"First, show me the current project structure"
6
7# Discuss approach
8"What's the best way to implement JWT auth in this Next.js app?"
9
10# Create checkpoint before changes
11/checkpoint "Before auth implementation"
12
13# Implement feature
14"Create the authentication system with login, signup, and JWT"
15
16# Review changes
17/git diff
18
19# Run tests
20"Run the test suite and fix any failures"
21
22# Commit with AI-generated message
23/commit

2. Debugging an Issue

bash
1# Start with error context
2claude "Users are getting 500 errors on login"
3
4# Show relevant files
5/read src/api/auth.ts
6
7# Analyze the issue
8"What's causing the 500 error in this auth endpoint?"
9
10# Apply fix
11"Fix the authentication error"
12
13# Test the fix
14"Create a test case that reproduces the original issue"
15
16# Verify fix works
17"Run the new test to confirm the fix"

3. Code Review

bash
1# Review recent changes
2claude "Review my recent changes for potential issues"
3
4# Check git diff
5/git diff
6
7# Get specific feedback
8"Are there any security vulnerabilities in these changes?"
9
10# Check best practices
11"Does this code follow React best practices?"
12
13# Suggest improvements
14"How can I optimize this code for performance?"

Advanced Features

Custom Tools

Claude Code supports custom tools via MCP (Model Context Protocol).

typescript
1// 📁 ~/.claude/tools/custom-tool.ts
2
3import { Tool } from '@anthropic-ai/claude-code';
4
5export const myCustomTool: Tool = {
6  name: 'analyze-bundle',
7  description: 'Analyze webpack bundle size',
8  execute: async (args) => {
9    // Your tool implementation
10  }
11};

Hooks

Automate actions with hooks:

yaml
1# 📁 ~/.claude/hooks.yaml
2
3# Run before each commit
4pre-commit:
5  - npm run lint
6  - npm test
7
8# Run after file edits
9post-edit:
10  - npm run format
11
12# Run on session start
13on-start:
14  - git fetch
15  - npm install

Environment-Specific Settings

yaml
1# 📁 .claude.yaml (project root)
2
3# Project-specific configuration
4model: claude-sonnet-4-5
5auto_approve: false
6
7# Custom ignore patterns
8ignore:
9  - "**/*.test.ts"
10  - "node_modules/"
11  - ".next/"
12  - "dist/"
13
14# Custom commands
15commands:
16  test: npm test
17  build: npm run build
18  deploy: npm run deploy
19
20# Project memory
21memory:
22  - "This is a Next.js 14 app with App Router"
23  - "Uses TypeScript strict mode"
24  - "Tailwind CSS for styling"
25  - "Prefer server components by default"

Best Practices

Effective Prompting

Pro Tip: Specific prompts get better results. Instead of "fix this," try "fix the null pointer error in getUserData when user is not found"

❌ Vague Prompts

  • "Make it better"
  • "Fix the bug"
  • "Add validation"

✅ Specific Prompts

  • "Refactor this function to use async/await and add error handling"
  • "Fix the race condition in the login flow where tokens expire during requests"
  • "Add Zod validation for email, password (min 8 chars), and username fields"

Context Management

  1. Start Broad, Then Narrow

    bash
    "Show me the project structure"
    "Now focus on the authentication module"
    "Let's look at the login function specifically"
  2. Provide Relevant Context

    bash
    "I'm using Next.js 14 with Server Actions"
    "The auth system uses JWT with httpOnly cookies"
    "Following the repository pattern for data access"
  3. Use Checkpoints for Experiments

    bash
    1/checkpoint "stable-auth"
    2# Try experimental approach
    3# If it doesn't work:
    4/restore "stable-auth"

Security Best Practices

Security Alert: Never paste API keys, passwords, or sensitive data directly into Claude Code. Use environment variables!

bash
1# ❌ DON'T DO THIS
2claude "Add this API key to the config: sk-1234567890"
3
4# ✅ DO THIS INSTEAD
5claude "Update config to read API key from ANTHROPIC_API_KEY environment variable"

Troubleshooting

Common Issues

Issue: "API key not found"

bash
1# Solution: Set environment variable
2export ANTHROPIC_API_KEY="your-api-key"
3
4# Or add to shell profile
5echo 'export ANTHROPIC_API_KEY="your-key"' >> ~/.bashrc
6source ~/.bashrc

Issue: "Rate limit exceeded"

bash
1# Solution: Check usage and wait
2claude config set rate_limit_wait true
3
4# Or check your usage
5/cost

Issue: "Context window exceeded"

bash
1# Solution: Use .claudeignore to exclude large files
2echo "node_modules/" >> .claudeignore
3echo "dist/" >> .claudeignore
4echo "*.log" >> .claudeignore
5
6# Or clear conversation history
7/clear

Issue: "File too large to process"

bash
1# Solution: Increase max file size or exclude file
2claude config set max_file_size 20MB
3
4# Or add to .claudeignore
5echo "large-dataset.json" >> .claudeignore

Performance Optimization

Optimizing Token Usage

yaml
1# 📁 .claudeignore
2
3# Exclude dependencies
4node_modules/
5.venv/
6vendor/
7*.min.js
8
9# Exclude build artifacts
10dist/
11build/
12.next/
13out/
14
15# Exclude large data files
16*.csv
17*.json.gz
18*.db
19*.sqlite
20
21# Exclude media
22*.png
23*.jpg
24*.gif
25*.mp4
26
27# Exclude logs and caches
28*.log
29.cache/
30.turbo/

Batch Operations

bash
1# Instead of multiple requests:
2"Fix linting errors in Button.tsx"
3"Fix linting errors in Input.tsx"
4"Fix linting errors in Card.tsx"
5
6# Use one request:
7"Fix all linting errors in components/ directory"

Quick Reference Templates

React Component Template

typescript
1// 📁 components/ComponentName.tsx
2
3'use client'
4
5import { useState } from 'react';
6
7interface ComponentNameProps {
8  // Props interface
9}
10
11export function ComponentName({ }: ComponentNameProps) {
12  const [state, setState] = useState();
13
14  return (
15    <div>
16      {/* Component content */}
17    </div>
18  );
19}

API Route Template (Next.js)

typescript
1// 📁 app/api/route-name/route.ts
2
3import { NextRequest, NextResponse } from 'next/server';
4
5export async function GET(request: NextRequest) {
6  try {
7    // Handle GET request
8    return NextResponse.json({ data: 'success' });
9  } catch (error) {
10    return NextResponse.json(
11      { error: 'Internal server error' },
12      { status: 500 }
13    );
14  }
15}
16
17export async function POST(request: NextRequest) {
18  try {
19    const body = await request.json();
20    // Handle POST request
21    return NextResponse.json({ data: 'success' });
22  } catch (error) {
23    return NextResponse.json(
24      { error: 'Internal server error' },
25      { status: 500 }
26    );
27  }
28}

Test Template

typescript
1// 📁 __tests__/component.test.tsx
2
3import { render, screen, fireEvent } from '@testing-library/react';
4import { ComponentName } from '@/components/ComponentName';
5
6describe('ComponentName', () => {
7  it('renders correctly', () => {
8    render(<ComponentName />);
9    expect(screen.getByText('Expected Text')).toBeInTheDocument();
10  });
11
12  it('handles user interaction', () => {
13    render(<ComponentName />);
14    fireEvent.click(screen.getByRole('button'));
15    expect(screen.getByText('Updated Text')).toBeInTheDocument();
16  });
17});

Comparison with Alternatives

FeatureClaude CodeGitHub CopilotCursorCodeium
CLI Interface✅ Native❌ No❌ No❌ No
Context Window200K tokens~8K tokens~32K tokens~16K tokens
Multi-File Editing✅ Yes⚠️ Limited✅ Yes⚠️ Limited
Checkpoints✅ Yes❌ No⚠️ Sessions only❌ No
Memory System✅ Yes❌ No⚠️ Limited❌ No
Git Integration✅ Advanced⚠️ Basic✅ Good⚠️ Basic
PricingAPI usage$10/month$20/monthFree tier

Additional Resources


Quick Command Reference Card

bash
1# Session Management
2claude                    # Start in current directory
3claude /path             # Start in specific directory
4/exit                    # Exit session
5Ctrl+D                   # Exit session
6
7# File Operations
8/read <file>             # Read file
9/edit <file>             # Edit file
10/create <file>           # Create file
11/glob <pattern>          # Find files
12
13# Git Operations
14/git status              # Git status
15/git diff                # Show changes
16/commit                  # AI commit message
17
18# Checkpoints
19/checkpoint <name>       # Save state
20/restore <name>          # Restore state
21/checkpoint list         # List checkpoints
22
23# Configuration
24claude config list       # View config
25claude config set <k> <v> # Set config
26/settings                # Open settings
27
28# Utilities
29/help                    # Show help
30/cost                    # Usage stats
31/memory show             # View memory
32/clear                   # Clear history

Bookmark This Page! Keep this cheatsheet handy for quick reference while coding with Claude Code.

Last updated: February 2024 | Claude Code v2.0

Was this cheatsheet helpful? Let us know!