Claude Code — Cheat Sheet 📋

"The page you print and pin next to your screen"

Claude Code architecture

SectionInstall & Setup

Claude Code is Anthropic's official terminal coding agent — it reads/edits files, runs shell commands, uses MCP servers, delegates to subagents, and can run headless.

bash
# macOS / Linux / WSL — native install (recommended)
curl-fsSLhttps://claude.ai/install.sh|bash

# Windows PowerShell
irmhttps://claude.ai/install.ps1|iex

# Windows CMD
curl-fsSLhttps://claude.ai/install.cmd-oinstall.cmd&&install.cmd&&delinstall.cmd

# Stable channel instead of latest
curl-fsSLhttps://claude.ai/install.sh|bash-sstable

# A specific version
curl-fsSLhttps://claude.ai/install.sh|bash-s2.1.89

# Homebrew (no auto-update)
brewinstall--caskclaude-code

# WinGet
wingetinstallAnthropic.ClaudeCode

# npm (needs Node.js 22+ — installs the SAME native binary; claude does NOT use your Node at runtime)
npminstall-g@anthropic-ai/claude-code
# ⚠️ NEVER: sudo npm install -g
Install & verify Claude Code
➜ ~ curl -fsSL https://claude.ai/install.sh | bash
installation takes a few seconds...
➜ ~ claude --version
2.1.211 (Claude Code)
➜ ~⏎ run · ⌫ clear
CommandWhat it doesWhen to useWhy it matters
claude --versionPrints the version numberConfirm your buildVerifies the install
claude doctorRead-only install + settings check (no session)Something's offDiagnoses without changing anything
claude updateUpdate to the latest versionManual updateHomebrew & pkg managers don't auto-update
claude (first run)Opens a session and prompts browser loginFirst runNeeds a Pro / Max / Team / Enterprise / Console account
claude setup-tokenGenerates a long-lived OAuth tokenFor CI & scriptsAuth without a browser

Auth: If the ANTHROPIC_API_KEY env var is set, Claude prompts once to approve the key instead of opening a browser. Enterprise providers: Amazon Bedrock, Google Cloud Vertex AI, Microsoft Foundry.

System requirements: macOS 13+ / Windows 10 1809+ / Ubuntu 20.04+ / Debian 10+ / Alpine 3.19+, 4GB+ RAM, x64/ARM64, ripgrep bundled. On native Windows, Git for Windows is optional (enables the Bash tool via Git Bash; otherwise it uses the PowerShell tool).

SectionCore CLI Commands

CommandWhat it doesWhen to useWhy it matters
claudeStart an interactive sessionDaily useThe main entry point
claude "query"Start with an initial promptJump in with a questionSaves a step
claude -p "query"Print mode: run via SDK, print, exitheadless / scriptsKey to automation
cat file | claude -p "query"Process piped contentAnalyze a log or fileCombine with terminal tools
claude -cContinue the most recent conversation in this dirResume your workNo need to recall the ID
claude -c -p "query"Continue via SDK (headless)Chained automationKeeps context
claude -r "<session>" "query"Resume a session by ID/name (or picker)Return to a specific chatPrecise session control
claude updateUpdate to the latest versionManual updateFor Homebrew & pkg managers
claude install [version]Install / reinstall the native binaryFix an installPins a specific version
claude doctorRead-only install + settings diagnosticsTroubleshootNo session needed
claude mcpConfigure MCP servers (subcommands below)Add external toolsWire up data/tools
claude agentsOpen agent view: monitor/dispatch parallel background sessionsMulti-task in parallelMonitoring for background agents
claude auth login / logout / statusSign in / out / show statusAccount managementSwitch accounts
claude setup-tokenLong-lived OAuth token for CIAuth in pipelinesAutomated auth
claude pluginManage pluginsAdd/remove pluginsExtend the tool
claude project purge [path]Delete local Claude state for a projectClean upStart fresh

SectionKey Flags

FlagWhat it doesWhen to use
-p, --printPrint response, no REPL (headless/SDK)Automation & scripts
-c, --continueLoad the most recent conversation in the cwdResume your work
-r, --resumeResume a specific session by ID/name (or picker)Return to a chat
--fork-sessionOn resume, make a new session id instead of reusingSafe forking
--modelSet the model by alias or full namePick Opus/Sonnet/Haiku
--fallback-modelAuto-fallback model(s) when the primary is overloadedReliability
--permission-modeStart in a permission mode (default/acceptEdits/plan/bypassPermissions)Control safety
--dangerously-skip-permissionsSkip all permission prompts (== bypassPermissions)Sandboxed envs only ⚠️
--allowedTools / --allowed-toolsTools that run without promptingTrusted automation
--disallowedTools / --disallowed-toolsDeny rules for toolsBlock certain tools
--toolsRestrict which built-in tools Claude may useNarrow permissions
--add-dirAdd extra working directories to read/editMulti-directory work
--output-formatPrint-mode output: text | json | stream-jsonProgrammatic parsing
--input-formatPrint-mode input: text | stream-jsonStreaming input
--json-schemaForce validated JSON output matching a schemaGuaranteed shape
--mcp-configLoad MCP servers from JSON file(s)/stringAd-hoc MCP setup
--strict-mcp-configUse only the servers from --mcp-configIsolate MCP
--append-system-promptAppend text to the default system promptExtra instructions
--system-promptReplace the whole system promptFull control
--agentsDefine subagents inline via JSONAd-hoc agents
--agentUse a specific agent for the sessionCustom behavior
--max-turnsCap the number of agentic turnsAutomation guardrail
--max-budget-usdStop after spending this many dollars on the APICost control
--session-idUse a specific UUID for the sessionProgrammatic linking
--settingsPath to settings JSON or inline JSONCustom config
--setting-sourcesWhich sources to load: user,project,localControl config
--verboseFull turn-by-turn outputDebugging
--worktree, -wStart in an isolated git worktreeWork on a separate feature
--permission-prompt-toolMCP tool to handle permission prompts non-interactivelyFull automation
--version, -vPrint the versionConfirm your build

SectionHeadless & Programmatic

bash
# One-shot: print and exit
claude-p"explain the root cause"

# Structured JSON output (result, cost, session_id...)
claude-p"summarize this diff"--output-formatjson

# Streaming NDJSON events — with streaming input
claude-p"refactor auth"--output-formatstream-json--input-formatstream-json

# Pipe content from another tool
caterror.log|claude-p"explain the root cause"

# Automation guardrails
claude-p"fix failing tests"\
--max-turns8\
--max-budget-usd2.00\
--allowedTools"Read,Edit,Bash(npm test:*)"\
--permission-modeacceptEdits\
--session-id123e4567-e89b-12d3-a456-426614174000

# Long-lived auth for CI
claudesetup-token

The Claude Agent SDK (TypeScript / Python) wraps all of this so you can build custom agents.

SectionPermission Modes

Permission modes

ModeWhat it doesWhen to use
defaultAsks the first time it uses each kind of toolNormal use — safest
acceptEditsAuto-accepts file edits (still asks for risky bash)Many trusted edits
planRead-only: plans and proposes, does not modify until you approveA big task that needs thought
bypassPermissionsNo prompts at all (dangerous — --dangerously-skip-permissions)Sandboxed envs only ⚠️

Switching: Shift+Tab cycles the modes (default → acceptEdits → plan → …). Or start directly in a mode with --permission-mode.

SectionSession & Conversation

CommandWhat it doesWhen to useWhy it matters
/clear (aliases: /reset, /new)Start a new conversation, empty context (keeps project memory)Start a new topicClean context = better results
/resumeReturn to an earlier conversationGet back to old workSaves time
/rewindRoll code and conversation back to a checkpointThe agent did something wrongUndoes edits and context together
/compact [instructions]Summarize the conversation to free contextYou're near the context limitKeeps the important bits, saves tokens
/branch [name]Branch the conversation at this pointTry a different pathExperiment without losing the original
/background [prompt] (alias /bg)Detach the session to run as a background agentWork in the backgroundLets you keep going
/fork <directive>Spawn a forked subagent that inherits the conversationIndependent side workInherits the context
/export [filename]Export the conversation as plain textShare or saveArchiving
/context [all]Visualize context usage as a colored gridUnderstand your contextKnow when to compact
/statusCurrent session statusQuick glanceDiagnostics
/cost (= /usage)Token usage + costsWatch spendCost control
/copy [N]Copy the last (or Nth-latest) response to clipboardGrab a reply fastPaste elsewhere
/btw <question>Quick side question, not added to the conversationA simple questionDoesn't pollute context

SectionAll Slash Commands

Built-in

CommandWhat it doesWhen to use
/add-dir <path>Add a working dir for this sessionWork in another dir
/agentsManage subagent configurationsCreate/edit agents
/cd <path>Move the session to a new working dirChange work location
/chromeConfigure Claude in ChromeBrowser integration
/color [color|default]Set the prompt bar colorCustomize the look
/config [key=value] (alias /settings)Open Settings or set a setting directlyChange configuration
/desktop (alias /app)Continue this session in the Desktop appMove to the GUI
/diffInteractive diff viewer of uncommitted changesSee what changed
/exit (alias /quit)Exit the CLIClose
/fast [on|off]Toggle fast modeFaster replies
/focusToggle focus viewFocused display
/helpShow help + available commandsLearn the commands
/hooksView hook configurations for tool eventsReview hooks
/ideManage IDE integrations + show statusConnect the editor
/initInitialize the project with a CLAUDE.md guideNew project
/keybindingsOpen your keyboard shortcuts fileCustomize keys
/login / /logoutSign in / outAccount management
/mcp [reconnect|enable|disable]Manage MCP connections + OAuthManage MCP
/memoryEdit CLAUDE.md memory files + manage auto-memoryUpdate memory
/mobile (aliases /ios, /android)QR to download the mobile appMove to mobile
/model [model]Switch model, save as defaultChange the model
/permissions (alias /allowed-tools)Manage allow/ask/deny tool rulesControl permissions
/rewindRoll code and conversation back to a checkpointUndo
/statusCurrent session statusQuick glance
/tasksList this session's background workMonitor background work
/teleportPull a web session into this terminalMove from the web
/remote-controlContinue a local session from another deviceRemote control
/usage (alias /cost)Token usage + costsWatch spend

Bundled skills (ship with Claude Code)

CommandWhat it doesWhen to use
/code-review [level] [--fix] [--comment] [target]Review the diff for bugs + cleanups — ultra = deep cloud multi-agent reviewBefore a merge
/security-reviewCheck the diff for security vulnerabilitiesConfirm no vulnerabilities
/simplifyCleanup-only review that applies fixes (no bug hunting)Tidy up the code
/planSwitch into plan mode before a large changePlan first
/debug [description]Enable debug logging + troubleshootFix problems
/deep-research <question>Fan out web searches + synthesize a cited reportDeep research
/fork <directive>Spawn a forked subagent that inherits the conversationSide work
/goal [condition|clear]Keep working until a condition is metA task with a clear goal
/loop [interval] [prompt] (alias /proactive)Run a prompt repeatedly while the session stays openMonitoring
/batch <instruction>Orchestrate large-scale parallel changes across a codebaseBulk edits
/dataviz [request]Design guidance for charts/dashboardsData design
/claude-apiLoad Claude API reference materialWork on the API
/fewer-permission-promptsScan transcripts + add an allowlistFewer prompts
/install-github-appInstall the Claude GitHub App for a repoGitHub integration
/doctor (alias /checkup)Setup checkup that diagnoses/fixes issuesDiagnostics

Aliases: /settings=/config · /reset,/new=/clear · /cost=/usage · /bug,/share=/feedback · /quit=/exit · /checkup=/doctor · /allowed-tools=/permissions · /bg=/background · /app=/desktop · /proactive=/loop.

SectionDelegation & Subagents

Subagents are specialized AI assistants that handle a specific kind of task in their own context window, with their own system prompt, tool access, and permissions — and they return only a summary to the main chat.

Why they matter: (1) preserve the main context, (2) enforce tool constraints, (3) reuse config across projects, (4) specialize behavior, (5) control cost by routing tasks to cheap/fast models like Haiku.

How delegation happens: Claude reads each subagent's description and delegates automatically when a task matches. You can also force it:

bash
>Usethecode-reviewersubagenttocheckmychanges

Managing them & file locations:

LocationPurpose
/agentsCreate/edit/view, set tools and model
.claude/agents/<name>.mdProject-level agent (shared via git)
~/.claude/agents/<name>.mdPersonal agent (all your projects)
claude agents / --bgRun many independent parallel sessions and monitor them
--agents (flag)Define subagents inline via JSON

Frontmatter fields: name · description (when to use it — write it well!) · tools (optional; omit = inherit all) · model (optional: sonnet/opus/haiku or 'inherit').

yaml
---
name: code-reviewer
description: Expert code review specialist. Use PROACTIVELY after writing or changing code.
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a senior code reviewer. When invoked: run git diff, focus on changed files, review for
readability, bugs, security. Give feedback grouped by priority.

Mental model: the main agent = orchestrator; subagents = focused workers with clean context; only the summary comes back.

SectionCustom Commands (Skills)

Custom commands are merged into skills. .claude/commands/deploy.md and .claude/skills/deploy/SKILL.md both make /deploy.

LocationScope
.claude/commands/ or .claude/skills/Project (shared via git)
~/.claude/commands/ or ~/.claude/skills/Personal

Frontmatter fields: description · argument-hint · allowed-tools · model · (skills add) invocation control + run-in: subagent.

Body specials:

  • $ARGUMENTS = everything typed after the command · $1, $2, … = positional args.
  • ! at the start of a line = run a bash command and embed its output (needs allowed-tools Bash).
  • @path/to/file = embed a file's contents.

Namespacing: subdirectories → /frontend:lint, /backend:deploy. Skills load their body only when used (cheap until needed). Claude can auto-invoke a skill when relevant, or you invoke /name.

markdown
---
description: Create a git commit
argument-hint: [message]
allowed-tools: Bash(git add:*), Bash(git commit:*)
model: claude-haiku-4-5
---
## Context
- Current status: !`git status`
- Current diff: !`git diff HEAD`
## Task
Create a single commit with message: $ARGUMENTS

SectionMemory & Config

CLAUDE.md = persistent instructions, auto-loaded. Hierarchy (all concatenate, later can add to earlier):

PriorityFileScope
1Enterprise/managed policy (system dir)Org policy
2~/.claude/CLAUDE.mdAll your projects
3./CLAUDE.mdThe project (shared via git)
4./CLAUDE.local.mdPersonal (gitignored) — being deprecated for imports
  • Nested CLAUDE.md in subdirs load on demand when Claude touches files there.
  • /init = scaffold a CLAUDE.md for the project.
  • /memory = open + edit memory files.
  • # at the start of input = "remember this" → appends a line to a memory file.
  • @path/import.md inside CLAUDE.md = import another file (max 5 hops).
  • Auto-memory: Claude writes notes to ~/.claude/projects/<project>/memory/ (MEMORY.md index). Survives /compact. Gitignored.
  • Path-scoped rules: .claude/rules/*.md with paths: frontmatter globs load only when Claude reads matching files.

settings.json hierarchy (precedence high → low)

text
Managed(org)command-lineflags.claude/settings.local.json(personal,gitignored)
  → .claude/settings.json (project, shared) → ~/.claude/settings.json (user)

Key fields: model · permissions {allow, ask, deny, defaultMode} · env · hooks · autoUpdatesChannel · minimumVersion · editorMode ("vim"/"normal") · autoMemoryEnabled · outputStyle.

SectionHooks

Deterministic handlers (shell/HTTP/…) fired at lifecycle events (settings.json → hooks).

EventWhen it fires
SessionStartSession begins/resumes (matchers: startup, resume, clear, compact)
UserPromptSubmitYou submit a prompt, before Claude sees it
PreToolUseBefore a tool call runs (can allow/deny/ask)
PostToolUseAfter a tool call succeeds
PostToolUseFailureAfter a tool call fails
NotificationClaude sends a notification (e.g. needs input)
StopClaude finishes responding
SubagentStart / SubagentStopA subagent spawns / finishes
PreCompact / PostCompactAround context compaction
SessionEndThe session terminates

There are more: PermissionRequest, PermissionDenied, TaskCreated/Completed, FileChanged, WorktreeCreate/Remove, etc.

json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "if": "Bash(rm *)",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh",
            "args": []
          }
        ]
      }
    ]
  }
}
  • Matcher: ""/"*"/omitted = all · plain string = exact (e.g. "Edit|Write") · other chars = regex.
  • Hook types: command, http, mcp_tool, prompt, agent. Common fields: if, timeout (default 600s), statusMessage.
  • Exit codes: 0 = ok (stdout may carry JSON) · 2 = BLOCK (stderr → Claude) · other = non-blocking error.
  • JSON control (PreToolUse): {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"..."}} — values allow/deny/ask/defer.
  • Universal JSON: continue (false stops Claude) · stopReason · suppressOutput · systemMessage · additionalContext.
  • Path vars: ${CLAUDE_PROJECT_DIR} · ${CLAUDE_PLUGIN_ROOT}.

SectionMCP

Connect external tools/data.

bash
# stdio
claudemcpadd<name>--<command>[args]

# SSE / HTTP
claudemcpadd--transportsse<name><url>
claudemcpadd--transporthttp<name><url>

# From JSON
claudemcpadd-json<name>'<json>'

# Import from Claude Desktop
claudemcpadd-from-claude-desktop

# List / details / remove
claudemcplist
claudemcpget<name>
claudemcpremove<name>
ScopeMeaning
local (default)This project only
projectShared via .mcp.json in the repo
userAll your projects
  • In the REPL: /mcp shows servers + status, does OAuth login (/mcp → authenticate), reconnect/enable/disable.
  • Use resources in prompts: @server:protocol://resource.
  • MCP servers can expose prompts as slash commands: /mcp__server__promptname.
json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_TOKEN": "..." }
    }
  }
}

SectionPermission Rules

allow/ask/deny rules in settings.json (permissions.allow/ask/deny):

RuleMeaning
Read, Edit, Write, Bash, WebFetch, WebSearch, GrepA whole tool
Bash(npm run test:*)Prefix match
Bash(git *)All git commands
Bash(git status)Exact command
Read(./src/**)Read a specific path
Read(//etc/**)Absolute path
deny Read(./.env)Block reading a sensitive file
deny Read(./secrets/**)Block a whole folder
mcp__server__toolA specific MCP tool

/permissions opens the rules UI. defaultMode in settings sets the starting mode.

SectionShortcuts & Input

Prefixes at the start of a line:

SymbolWhat it does
/slash command / skill
!bash mode (run shell directly)
@file-path mention/autocomplete
#add to memory
ShortcutFunction
Shift+TabCycle permission modes (default → acceptEdits → plan → …)
EscInterrupt Claude / close a dialog
Esc Esc (double, empty input)Open the rewind/checkpoint menu
Ctrl+CCancel current input/operation
Ctrl+DExit
Ctrl+LClear screen (keeps session)
Ctrl+RReverse-search history / toggle verbose
Ctrl+OToggle transcript / expand
Ctrl+V (Cmd+V on some terms)Paste an image
Up/DownCommand history
Multiline\ + Enter, or Option/Alt+Enter, or Ctrl+J
Vim modeEnable via /config (editorMode: vim): Esc→NORMAL, i/a→INSERT, hjkl, dd, yy, p, u, .

Image input: drag/paste screenshots for Claude to analyze.

SectionEnv Vars & Config Paths

Env varWhat it does
ANTHROPIC_API_KEYAPI key; Claude prompts once to approve instead of a browser
DISABLE_AUTOUPDATER=1Disable the background update check
DISABLE_UPDATES=1Block all updates
CLAUDE_CODE_GIT_BASH_PATHPath to Git Bash on Windows (enables the Bash tool)
USE_BUILTIN_RIPGREPControls use of the bundled ripgrep
PathPurpose
~/.claude/settings.jsonUser settings
.claude/settings.jsonProject settings (shared)
.claude/settings.local.jsonPersonal settings (gitignored)
~/.claude/CLAUDE.mdUser memory
./CLAUDE.mdProject memory
.mcp.jsonProject-level MCP
.claude/agents/Subagent definitions
.claude/commands/Custom commands

SectionQuick Comparison

DimensionClaude CodeGitHub Copilot CLIOpenCode
MakerAnthropicGitHubCommunity (open source)
Default modelClaude (Opus/Sonnet/Haiku)Claude Sonnet 4.5Configurable
Model choiceClaude family (+ Bedrock/Vertex/Foundry)Multi (Claude, GPT-5)Any provider (Ollama, OpenAI, Anthropic…)
Subagents/Delegation.claude/agents/, /agents✅ subagents + rubber-duck✅ primary + sub
Custom commands✅ skills / .claude/commands/✅ skills
Hooks✅ rich lifecycle✅ 9 types
MCP✅ stdio/SSE/HTTP + scopes✅ (+ built-in GitHub MCP)
Permission modes✅ default/acceptEdits/plan/bypass✅ Allow/Ask/Deny
Plan mode
Checkpoints/rewind/rewind, Esc Esc/rewindpartial
Headless / SDK-p, Agent SDK-p
Background agentsclaude agents, --bg/delegate cloud
IDE ext✅ VS Code + JetBrains
CostPro $20 / Max / API / ConsoleCopilot sub $10–39/moFree + your API keys
SourceProprietary binaryProprietary (MIT-licensed CLI)Open source