agent:~/.claude$ cat claude-code-cheatsheet.md

Claude Code Cheat Sheet: Commands, Config, and Shortcuts

# Claude Code cheat sheet — every command, config key, hook event, keyboard shortcut, and CLI flag in one scannable reference. The quick-lookup companion to the full guide.

words: 3171 read_time: 16m updated: 2026-03-28 00:00
$ less claude-code-cheatsheet.md

Every CLI flag, slash command, keyboard shortcut, config key, hook event, and environment variable in one place. For deep explanations, see the full Claude Code guide. For first-time setup, see the quickstart.


1. Installation

Three installation methods, in order of preference.

# Native binary (recommended)
curl -fsSL https://claude.ai/install.sh | bash

# Homebrew (macOS)
brew install --cask claude-code

# NPM (deprecated — migrate with `claude install`)
npm install -g @anthropic-ai/claude-code

Install a specific version:

curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58

Verify installation:

claude doctor

Authenticate:

claude auth login       # Log in or switch accounts
claude auth status      # Check current auth state
claude auth logout      # Clear stored credentials

2. CLI Flags

Flag Description Example
-p Print mode — single query, then exit claude -p "list TODOs"
-c Continue most recent session claude -c
-r, --resume Resume a named or numbered session claude -r "auth-refactor"
-n, --name Set session display name at startup claude -n "feature-x"
--model Override model for this session claude --model opus
--max-turns Limit autonomous turns claude -p "fix lint" --max-turns 10
--output-format Output as text, json, or stream-json claude -p "count files" --output-format json
--allowedTools Restrict available tools claude -p "fix" --allowedTools "Edit,Bash(npm:*)"
--permission-mode Set permission mode claude --permission-mode auto
--enable-auto-mode Start with Auto Mode enabled claude --enable-auto-mode
--dangerously-skip-permissions YOLO mode — skip all prompts claude --dangerously-skip-permissions
--from-pr Start session linked to a pull request claude --from-pr 123
--fork-session Fork from a resumed session claude -r base --fork-session
-w Start in isolated git worktree claude -w
--bare Scripted mode — skip hooks, LSP, plugins claude -p "count files" --bare
--channels Relay approval prompts to Telegram/Discord claude --channels
--debug Enable debug logging claude --debug
--init Initialize project with CLAUDE.md claude --init

3. Slash Commands

Command What It Does
/init Initialize project with CLAUDE.md
/compact Condense conversation history. Add focus: /compact focus on tests
/context View context window usage with actionable suggestions
/cost Display token usage and cost breakdown
/model Change model. /model opus, /model sonnet
/fast Toggle fast output mode
/effort Set effort level: low, medium, high
/status View session state, model, settings
/permissions Manage permission settings interactively
/config Open full settings interface
/mcp Configure MCP servers. /mcp enable, /mcp disable
/hooks View hook configuration
/memory View and manage auto-memory files
/copy Copy code blocks. /copy N for Nth-latest response
/resume Resume named session. /resume 1 or /resume name
/rename Name current session. /rename feature-auth
/branch Branch conversation for parallel exploration
/clear Clear conversation history
/plan Enter plan mode. /plan refactor the auth module
/vim Enable vim editing mode
/voice Toggle push-to-talk voice mode
/loop Recurring tasks. /loop 5m /foo runs every 5 min
/rewind Return to checkpoint (or press Esc twice)
/export Export conversation transcript
/add-dir Add working directories to expand file access
/agents Manage subagents
/bashes List background bash tasks
/tasks List background agents
/theme Manage syntax themes
/color Set prompt-bar color. /color default to reset
/simplify Review code for simplification
/batch Batch operations
/security-review Review code for vulnerabilities
/claude-api Build apps with Claude API/Anthropic SDK
/doctor Check installation health
/bug Report a bug to Anthropic
/release-notes View latest release notes
/login / /logout Authenticate or sign out in session

Custom commands: Create .claude/commands/my-command.md (project) or ~/.claude/commands/my-command.md (personal) and invoke with /my-command. Commands support YAML frontmatter for description, allowed tools, model override, and argument interpolation via $ARGUMENTS or positional $1, $2.

---
description: Fix a GitHub issue
allowed-tools: Read, Edit, Bash(git:*)
model: opus
argument-hint: [issue-number]
---

Fix GitHub issue #$ARGUMENTS following our coding standards.

Usage: /fix-issue 123


4. Keyboard Shortcuts

General Controls

Shortcut Action
Ctrl+C Cancel current operation
Ctrl+D Exit session (EOF)
Ctrl+L Clear screen (keeps history)
Ctrl+O Toggle verbose output
Ctrl+R Search command history
Ctrl+V Paste image from clipboard
Ctrl+B Background current operation
Ctrl+F Kill all background agents
Ctrl+S Stash prompt draft
Ctrl+G Open external editor
Esc Esc Rewind last change
Tab Accept prompt suggestion
! Tab Bash history autocomplete
Shift+Tab Cycle permission modes
Alt+P / Option+P Switch models while typing
Alt+T Toggle thinking mode
Ctrl+T Toggle syntax highlighting
Shift+Down Cycle agent team teammates
Up/Down Navigate command history
? Show shortcuts

Quick Prefixes

Prefix Action Example
# Add to persistent memory # Always use TypeScript
/ Slash command /review
! Execute bash directly ! git status
@ Reference a file @src/index.ts
& Send task to cloud & Build the API

Multiline Input

Method Keys
Escape newline \ then Enter
macOS Option+Enter
iTerm2/WezTerm/Ghostty/Kitty Shift+Enter
Other terminals Shift+Enter (run /terminal-setup first)
Control character Ctrl+J

Keybindings are customizable via /keybindings (stored in ~/.claude/keybindings.json).


5. Configuration Files

Precedence Hierarchy (highest to lowest)

Level Location Scope
Enterprise (locked) /Library/Application Support/ClaudeCode/managed-settings.json (macOS) All users, cannot override
CLI flags Command-line arguments Current session
Local project .claude/settings.local.json Personal, current project (gitignored)
Shared project .claude/settings.json Team, checked into git
User global ~/.claude/settings.json All your projects
Runtime state ~/.claude.json OAuth tokens, MCP config

First match wins. Enterprise settings cannot be bypassed.


6. Settings.json Reference

Key settings with types and examples. Place in any settings file from the hierarchy above.

{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "model": "claude-sonnet-4-6",
  "permissions": {
    "allow": ["Read", "Glob", "Grep", "Bash(npm run:*)", "Bash(git:*)", "Edit(src/**)"],
    "deny": ["Read(.env*)", "Bash(rm -rf:*)", "Bash(sudo:*)"],
    "ask": ["WebFetch", "Bash(docker:*)"],
    "defaultMode": "acceptEdits",
    "additionalDirectories": ["../shared-lib"]
  },
  "env": {
    "NODE_ENV": "development"
  },
  "hooks": {},
  "sandbox": {
    "enabled": false,
    "autoAllowBashIfSandboxed": true
  },
  "includeCoAuthoredBy": true,
  "cleanupPeriodDays": 30,
  "respectGitignore": true,
  "showTurnDuration": true,
  "language": "en",
  "autoMemoryDirectory": ".claude/memory",
  "plansDirectory": ".claude/plans"
}

Permission rule syntax: Tool(pattern:*) provides prefix matching. Bash(npm run test:*) allows npm run test, npm run test:unit, etc. File patterns use glob syntax: Edit(src/**).

For the complete settings schema, see the Configuration Deep Dive in the full guide.


7. CLAUDE.md Quick Reference

CLAUDE.md is your project’s instruction file. Claude reads it at the start of every session.

Where it lives:

Location Scope
CLAUDE.md (project root) All users, all sessions in this project
.claude/CLAUDE.md Same, alternative location
~/.claude/CLAUDE.md Personal, all projects

What to include:

# Project Name

## Stack
- Backend: FastAPI, Python 3.11+
- Frontend: HTMX + Alpine.js + Bootstrap 5

## Commands
- Dev: `uvicorn app.main:app --reload --port 8000`
- Test: `python -m pytest -v`
- Lint: `ruff check .`

## Conventions
- Conventional commits: feat:, fix:, docs:, refactor:
- Never force push to main
- Always activate venv before Python commands

## Key Files
- app/main.py — FastAPI app and routes
- app/models.py — SQLAlchemy models

Keep it scannable. Dense prose wastes context tokens every session. Use bullet points, tables, and short code blocks. Avoid long paragraphs — Claude reads CLAUDE.md at the start of every session, so every word costs context.

Pro tips: - Use # prefix in the REPL to add things to auto-memory without editing CLAUDE.md: # Always use TypeScript strict mode - CLAUDE.md in subdirectories is loaded when Claude reads files in that directory - Team-shared rules go in .claude/rules/*.md for modular organization


8. Permission Modes

Mode Behavior Use Case
default Prompts on first use of each tool Normal development
acceptEdits Auto-approves file edits, prompts for bash Trusted projects
auto Classifier (Sonnet 4.6) reviews each action for safety Autonomous with safeguards
plan Read-only — no edits or execution allowed Analysis and planning only
bypassPermissions Skips all prompts CI/CD automation

Auto Mode (v2.1.85+) is the recommended replacement for --dangerously-skip-permissions. Read-only and file edits are auto-approved. Custom allow/deny rules resolve first. Everything else goes to the safety classifier. Auto-blocked by default: curl | bash, force-push to main, production deploys, mass cloud deletions, IAM changes, sending sensitive data externally.1

Circuit breaker: 3 consecutive blocks or 20 total in a session pauses back to manual prompting.

# Enable at startup
claude --enable-auto-mode

# Cycle during session
Shift+Tab    # default -> acceptEdits -> auto -> plan

9. Hook Events

Event When It Fires Can Block?
PreToolUse Before tool executes Yes
PostToolUse After tool completes No
PostToolUseFailure After tool fails No
UserPromptSubmit User sends a prompt Yes
Stop Claude finishes response Yes
SubagentStart Subagent spawns No
SubagentStop Subagent completes Yes
SessionStart Session begins No
SessionEnd Session closes No
Notification Alert triggered No
Setup --init/--maintenance flags No
InstructionsLoaded CLAUDE.md loaded No
ConfigChange Config file changes mid-session Yes
WorktreeCreate Worktree being created Yes
WorktreeRemove Worktree being removed No
PreCompact Before context compaction No
PostCompact After context compaction No
Elicitation MCP requests structured input Yes
ElicitationResult User responds to MCP dialog Yes
StopFailure Turn ends due to API error No
PermissionRequest Permission dialog shown Yes
TeammateIdle Agent team member idles Yes
TaskCompleted Task marked complete Yes

For the full hook protocol (input/output JSON, matchers, exit codes), see Hooks Deep Dive in the full guide.


10. Hook Configuration

Hooks live in settings.json or a dedicated hooks.json. Minimal example:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$FILE_PATH\""
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/validate-bash.sh"
          }
        ]
      }
    ]
  }
}

Matcher syntax:

Pattern Matches
* All tools
Bash Bash only
Edit\|Write Edit or Write
mcp__github MCP server tools
"" (empty) Events without tools (e.g., UserPromptSubmit)

Exit codes:

Code Meaning
0 Success — operation proceeds
2 Block — operation stops, stderr fed to Claude
1, 3+ Non-blocking warning

Async hooks run in the background without blocking: add "async": true to the hook object.2


11. MCP Quick Setup

Add an MCP server in one command:

# Remote HTTP server (recommended)
claude mcp add --transport http github https://api.githubcopilot.com/mcp/

# Remote with auth header
claude mcp add --transport http api https://api.example.com/mcp \
  --header "Authorization: Bearer $TOKEN"

# Local stdio server
claude mcp add --transport stdio postgres \
  --env "DATABASE_URL=postgresql://user:pass@localhost/db" \
  -- npx -y @anthropic-ai/mcp-server-postgres

Scope control:

claude mcp add --scope project ...   # Team-shared (.mcp.json)
claude mcp add --scope user ...      # Personal (~/.claude.json)

Project .mcp.json example:

{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/"
    },
    "database": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@anthropic-ai/mcp-server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost/db"
      }
    }
  }
}

MCP now has 100 million monthly downloads and 3,000+ indexed servers.3 For transport types, elicitation, and tool search configuration, see the MCP section in the full guide.


12. Subagent Types

Type Default Model Mode Use For
Explore Haiku (fast) Read-only Codebase search, finding files, understanding structure
General-purpose Inherits main Full read/write Complex research + modification tasks
Plan Inherits main Read-only Planning implementations before execution
Custom Configurable Configurable Domain-specific work (security review, testing, etc.)

Claude automatically delegates to subagents. You can also request them explicitly:

> Use the explore agent to find all auth-related files
> Have a subagent analyze the database schema

Custom subagents are defined in .claude/agents/ (project) or ~/.claude/agents/ (personal) as markdown files with YAML frontmatter. Up to 10 subagents can run in parallel.4

Custom agent frontmatter fields:

Field Purpose
name Unique identifier (lowercase, hyphens)
description When to invoke (include “PROACTIVELY” for auto-delegation)
tools Comma-separated tool list. Supports Agent(Explore) to restrict spawnable types
disallowedTools Tools to deny from inherited set
model opus, sonnet, haiku, or inherit (default)
permissionMode default, acceptEdits, plan, bypassPermissions, etc.
maxTurns Maximum agentic turns
background true to always run as background task
isolation worktree for isolated git worktree copy

Example custom agent (.claude/agents/security-reviewer.md):

---
name: security-reviewer
description: Expert security code reviewer. Use PROACTIVELY after code changes to auth or data handling.
tools: Read, Grep, Glob, Bash
model: opus
permissionMode: plan
---

You are a senior security engineer. Analyze for OWASP Top 10 vulnerabilities,
secrets, hardcoded credentials, and SQL injection. Report findings with severity
levels and remediation steps.

13. Environment Variables

Authentication and API

Variable Purpose
ANTHROPIC_API_KEY Direct API authentication
ANTHROPIC_AUTH_TOKEN Custom authorization header
ANTHROPIC_CUSTOM_HEADERS Additional request headers

Model Configuration

Variable Purpose
ANTHROPIC_MODEL Override default model
CLAUDE_CODE_SUBAGENT_MODEL Model for subagents
MAX_THINKING_TOKENS Enable extended thinking
CLAUDE_CODE_MAX_OUTPUT_TOKENS Limit output length

Cloud Providers

Variable Purpose
CLAUDE_CODE_USE_BEDROCK=1 Use AWS Bedrock
CLAUDE_CODE_USE_VERTEX=1 Use Google Vertex AI
CLAUDE_CODE_USE_FOUNDRY=1 Use Microsoft Foundry

Behavior Control

Variable Purpose
DISABLE_AUTOUPDATER=1 Prevent automatic updates
DISABLE_TELEMETRY=1 Opt out of usage telemetry
DISABLE_COST_WARNINGS=1 Hide cost warnings
DISABLE_PROMPT_CACHING=1 Disable prompt caching globally
CLAUDE_CODE_DISABLE_1M_CONTEXT=1 Use standard 200K instead of 1M
CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS=1 Remove built-in commit/PR instructions

Tool Configuration

Variable Purpose
BASH_DEFAULT_TIMEOUT_MS Bash command timeout (default 30000)
BASH_MAX_TIMEOUT_MS Maximum bash timeout (default 600000)
MCP_TIMEOUT MCP server startup timeout (default 5000)
MCP_TOOL_TIMEOUT MCP tool execution timeout (default 30000)

Network and Proxy

Variable Purpose
HTTP_PROXY / HTTPS_PROXY Proxy configuration
NO_PROXY Bypass proxy for specific domains
CLAUDE_CODE_CLIENT_CERT mTLS certificate path

For the complete list, see Environment Variables in the full guide.


14. Cost Reference

Pricing per 1 million tokens (as of March 2026).5

Model Input Output Notes
Opus 4.6 $5.00 $25.00 Complex reasoning, architecture
Opus 4.6 (1M context) $10.00 $37.50 Long context surcharge on API billing
Sonnet 4.6 $3.00 $15.00 Daily coding default
Sonnet 4.6 (1M context) $6.00 $22.50 Large codebases
Haiku 4.5 $1.00 $5.00 Exploration, simple tasks

A typical session consumes 50K-200K input tokens and 10K-50K output tokens. Haiku session: $0.10-$0.45. Opus session: $0.50-$2.25.

The 1M context window is enabled by default for Max, Team, and Enterprise plans (no [1m] suffix required). API-only billing still incurs the long-context surcharge above 200K input tokens.

Switch models during a session:

/model opus       # Switch to Opus 4.6
/model sonnet     # Switch to Sonnet 4.6
/model haiku      # Switch to Haiku 4.5

Decision rule: Simple exploration goes to Haiku. Daily coding goes to Sonnet. Hard reasoning, architecture, and security analysis go to Opus. Use opusplan for complex refactoring (Opus plans, Sonnet executes).


15. Key File Locations

Path Purpose
~/.claude/settings.json User-global settings
~/.claude/keybindings.json Custom keyboard shortcuts
~/.claude/CLAUDE.md Personal instructions (all projects)
~/.claude/commands/ Personal slash commands
~/.claude/skills/ Personal skills
~/.claude/agents/ Personal subagent definitions
~/.claude.json Runtime state, OAuth tokens, MCP config
.claude/settings.json Project settings (shared via git)
.claude/settings.local.json Project settings (personal, gitignored)
.claude/CLAUDE.md Project instructions
.claude/commands/ Project slash commands
.claude/agents/ Project subagent definitions
.claude/skills/ Project skills
.claude/plans/ Plan mode output files
.claude/memory/ Auto-memory files
.mcp.json Project MCP server config
CLAUDE.md Project instructions (root alternative)

16. Changelog

Date Change
2026-03-28 Initial release of cheat sheet, covering Claude Code CLI through v2.1.85

17. References


This cheat sheet is the quick-lookup companion to the full Claude Code CLI guide. For setup walkthroughs, see the Claude Code quickstart. Last updated March 28, 2026.

NORMAL claude-code-cheatsheet.md EOF