Reference · Claude Code

The Claude Code Cheat Sheet

Everything worth keeping within arm's reach: the four building blocks, the CLI, the slash commands, the shortcuts, and the four config surfaces that actually decide what the agent can and cannot do.

Compiled 5 September 2026 from the official docs at code.claude.com/docs. Claude Code ships fast — treat version-specific rows as a snapshot, not a contract.

The four building blocks

Almost every Claude Code setup is some arrangement of these four. Knowing which one a problem belongs to is most of the work.

Skill

The playbook

A folder with a SKILL.md holding a repeatable procedure — a rubric, a checklist, a template. Loaded on demand, either when you type /name or when Claude decides it's relevant.

Subagent

The extra hands

A separate context window with its own prompt, tools, and model. Use it to fan work out in parallel, or to keep a noisy search out of your main transcript.

MCP server

The plug socket

A process exposing tools over JSON-RPC — your APIs, databases, and SaaS. Speaks stdio, HTTP, SSE, or WebSocket.

Hook

The seatbelt

A shell command fired at a lifecycle event. The only one of the four that runs outside the model's judgement — a PreToolUse hook exiting 2 blocks the call, whatever Claude intended.

The distinction that matters. CLAUDE.md and skills are context — they shape what Claude tries to do. Permissions and hooks are enforcement — they decide what actually runs. If a rule must hold every time, it does not belong in a markdown file.

CLI commands

Everyday

CommandWhat it does
claudeStart an interactive session
claude "query"Start interactive with an opening prompt
claude -p "query"Print mode — answer, then exit. The scripting entry point
cat f | claude -p "…"Pipe content in
claude -cContinue the most recent conversation in this directory
claude -r "<id|name>" "…"Resume a specific session
claude updateUpdate to the latest version
claude doctorRead-only install and settings diagnostics

Config & extensions

CommandWhat it does
claude mcpConfigure MCP servers — see §11
claude mcp login <name>Run a server's OAuth flow
claude pluginManage plugins
claude import [codex|gemini]Bring config over from another coding agent
claude project purge [path]Delete all local Claude Code state for a project
claude auth login|logout|statusAccount authentication
claude setup-tokenLong-lived OAuth token for CI and scripts

Background & remote sessions

CommandWhat it does
claude agentsAgent view — monitor and dispatch parallel background sessions
claude attach <id>Attach to a background session in this terminal
claude logs <id>Print recent output from a background session
claude stop|rm|respawn <id>Stop, remove, or restart a background session
claude daemon status|stopInspect or stop the background-session supervisor
claude remote-controlDrive this Claude Code from claude.ai

CLI flags

There are well over eighty. These are the ones that earn their keep.

Scope and permission

FlagEffect
--add-dirGive Claude extra working directories
--permission-modeStart in plan, acceptEdits, auto, dontAsk…
--allowedTools / --disallowedToolsSession-scoped allow and deny rules
--dangerously-skip-permissionsSkip prompts. Containers and VMs only
--settingsPath to a settings file, or inline JSON
--setting-sourcesWhich setting layers to load, e.g. user,project

Model and effort

FlagEffect
--modelSet the session model
--fallback-modelFall back when the primary is overloaded — sonnet,haiku
--effortlow · medium · high · xhigh · max
--autocompact <auto|tokens>Set the auto-compact window, e.g. 500k

Scripting and automation

FlagEffect
--output-formattext, json, or stream-json
--json-schemaValidated JSON output matching a schema you supply
--max-turnsCap agentic turns
--max-budget-usdHard spend ceiling for the run
--append-system-promptAppend to the system prompt (--system-prompt replaces it)
--agentsDefine subagents inline as JSON, session-only
--mcp-config / --strict-mcp-configLoad MCP servers from a file; ignore all others
--bareSkip auto-discovery of hooks, skills, and custom commands
--safe-modeStart with every customization disabled

Debugging a setup? --bare and --safe-mode are the fastest bisect you have. If the problem disappears under --safe-mode, it is yours, not Claude's.

Slash commands

Context and session

CommandWhat it does
/contextVisualize context usage as a colored grid. The first thing to run when things feel slow
/compact [instructions]Summarize the conversation to free context
/clear [name]Start fresh with empty context
/rewindRoll code and conversation back to a checkpoint
/resumeReturn to an earlier conversation
/branch [name]Branch the conversation here to try another direction
/fork [prompt]Copy the conversation into a background session, keep working here
/usage · /costToken usage and cost for this session
/export [file]Export the conversation as plain text

Configuration

CommandWhat it does
/config · /settingsSettings UI — theme, model, output style
/permissionsView and edit allow / ask / deny rules, with their source file
/hooksView hook configuration for tool events
/mcpMCP connections and OAuth
/skillsManage custom and bundled skills
/pluginInstall and manage plugins
/memoryEdit CLAUDE.md files, toggle auto memory
/model · /effort · /fastModel, effort level, fast mode
/keybindingsOpen your keyboard shortcuts file
/add-dir · /cdAdd a working directory · move the session

Work

CommandWhat it does
/initGenerate a starting CLAUDE.md from the codebase
/plan [description]Enter plan mode straight from the prompt
/code-review · /reviewReview the diff, a PR number, a branch, or a path. Takes an effort level, plus --fix and --comment
/security-reviewCheck the diff for security vulnerabilities
/simplifyCleanup pass — reuse, simplification, efficiency. No bug hunting
/diffReview the working tree, Claude's edits included
/subtaskHand a side task to a subagent, result returns here
/batch <instruction>Large-scale parallel changes across a codebase
/loop [interval] [prompt]Run a prompt repeatedly while the session is open
/worktreeGit worktrees for isolated changes
/todos · /goalTask list · keep working until a condition is met

Diagnostics

CommandWhat it does
/doctorSetup checkup that diagnoses and can fix issues
/debug [description]Turn on debug logging and troubleshoot
/statusCurrent session status
/insightsHTML report analyzing your recent local sessions
/skill-doctorFind unused skills and what they cost in context
/fewer-permission-promptsMine transcripts for safe read-only calls, propose an allowlist

Keyboard shortcuts

Control

KeyAction
EscInterrupt Claude, or close a dialog
Esc EscClear the input draft, or rewind
Ctrl+CInterrupt; if nothing runs, clear input, then exit on a second press
Ctrl+DExit the session
Shift+TabCycle permission modes
Ctrl+OToggle the transcript viewer
Ctrl+TToggle Claude's task checklist
Ctrl+BBackground the running task
Ctrl+RReverse-search command history
Ctrl+GOpen the prompt in your editor
Ctrl+SStash or restore the prompt
Ctrl+VPaste an image from the clipboard
Ctrl+X Ctrl+KStop all background subagents. Twice within 3s to confirm
Option/Alt+PSwitch model
Option/Alt+TToggle extended thinking
Option/Alt+OToggle fast mode
? on empty inputToggle the shortcut help panel

Prompt prefixes

PrefixMeaning
/Command or skill
!Shell mode — run the command directly
@File path mention, or @agent-<name> to force a subagent
#Ask Claude to remember something
:Emoji shortcode

Line editing

KeyAction
Ctrl+A / Ctrl+EStart / end of line
Ctrl+K / Ctrl+UDelete to end / to start of line
Ctrl+WDelete back to previous whitespace
Ctrl+YPaste deleted text (Alt+Y cycles paste history)
Alt+B / Alt+FBack / forward one word
Ctrl+_Undo the last input edit

Vim bindings are available too — turn them on with /vim or editorMode: "vim". NORMAL, INSERT, and visual modes, with text objects and f/t motions.

macOS: the Alt shortcuts need Option configured as Meta in your terminal. iTerm2, Terminal.app, and Ghostty each have their own setting for it.

Settings & precedence

Where settings live, highest priority first

#LayerFileWho it's for
1Managedmanaged-settings.json, MDM, consoleYour organization
2Command lineclaude --settingsYou, this session
3Project local.claude/settings.local.jsonYou, this project
4Shared project.claude/settings.jsonEveryone in the project
5User~/.claude/settings.jsonYou, every project

A key set higher wins. Lists — permission rules, claudeMdExcludes — merge across layers rather than overriding.

Keys worth knowing

KeyWhat it controls
permissionsallow / ask / deny rules and the starting mode
hooksYour commands at lifecycle events
envEnvironment variables for every session and subprocess
model · fallbackModel · availableModelsDefault model, backups, and the allowed list
effortLevel · modelSettingsDefault effort; saved per-model effort
sandbox.enabledIsolate Bash from filesystem and network (macOS, Linux, WSL2)
autoCompactEnabled · autoCompactWindowCompaction behavior
autoMemoryEnabled · autoMemoryDirectoryAuto memory on/off and where it's stored
claudeMd · claudeMdExcludesInject org-wide instructions · skip specific CLAUDE.md files
disableBundledSkills · skillOverridesTurn bundled skills off, or hide individual ones
disableAllHooksKill hooks, status line, and custom file suggestions at once
attributionCustomize or hide commit and PR attribution
statusLineRender your own status line below the prompt
editorModevim for vim bindings in the prompt
cleanupPeriodDaysHow long transcripts are kept
outputStyle · languageClaude's role and tone · response language
fileCheckpointingEnabledThe file snapshots /rewind restores
strictPluginOnlyCustomizationLock skills / agents / hooks / MCP to plugin and managed sources

The full list runs to roughly 180 keys, plus a deep sandbox.* tree for filesystem and network isolation. Full reference: settings-reference.

Permissions

Modes

ModeBehavior
defaultManual. Prompts on first use of each tool
acceptEditsAuto-accepts file edits and common filesystem commands in the working directory
planReads and explores, doesn't edit source
autoAuto-approves with a background classifier checking each action against your request
dontAskAuto-denies anything not pre-approved
bypassPermissionsSkips prompts. Isolated environments only

Rule syntax

Rules are Tool or Tool(specifier). They evaluate deny → ask → allow; first match wins, and specificity does not reorder them. A broad deny cannot carry an allowlist exception.

{
  "permissions": {
    "allow": [
      "Bash(npm run *)",
      "Bash(git commit *)",
      "Read(//home/me/project/**)",
      "mcp__github__get_*"
    ],
    "ask":   [ "Bash(git push *)" ],
    "deny":  [ "Read(./.env)", "Edit(./secrets/**)", "mcp__*" ]
  }
}

Wildcards — the part everyone gets wrong

RuleMatchesDoesn't match
Bash(npm run build)npm run buildnpm run build --watch
Bash(npm run *)npm run test --watch, bare npm runnpm install
Bash(git * main)git push origin main — every subcommandgit log
Bash(ls *)ls -la, lslsof
Bash(ls*)ls -la, lsof—

Put the * after the subcommand. Everything before the first * is matched literally, so that prefix is the whole of your rule's safety. Bash(git log *) allows only git log. Bash(git *) allows git push, and also git -c core.fsmonitor=<script>, which runs a program you named.

Other things to know: compound commands are split on && || ; | & and each part must match on its own; wrappers like timeout, nice, and bare xargs are stripped before matching, but npx, docker exec, and devbox run are not; a bare tool name in deny removes the tool from Claude's context entirely, while Bash(rm *) leaves Bash available and blocks matching calls.

Hooks

Shell commands fired at lifecycle events, configured in any settings file. Claude Code passes a JSON payload on stdin; your exit code and stdout JSON decide what happens next.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|Bash",
        "hooks": [
          { "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard.sh" }
        ]
      }
    ]
  }
}

Exit codes

CodeMeaning
0Success. stdout is parsed as JSON for a structured decision
2Block. On PreToolUse the call never runs and your stderr goes back to the model
otherNon-blocking error. Work continues

The events you'll actually use

EventFiresMatcherBlocks?
SessionStartSession begins or resumesstartup · resume · clear · compact · forkNo
UserPromptSubmitYou submit a prompt—Yes
PreToolUseBefore a tool runsTool name, regexYes
PostToolUseAfter a tool succeedsTool nameNo
PostToolUseFailureAfter a tool failsTool nameNo
PermissionRequestA call needs a decisionTool nameVia JSON
SubagentStart / SubagentStopSubagent spawns / finishesAgent typeStop: yes
StopClaude finishes responding—Yes
PreCompact / PostCompactAround compactionmanual · autoNo
NotificationA notification is sentNotification typeNo
SessionEndSession terminatesclear · logout · resume …No

There are 33 events in total, covering task lifecycle, config and file changes, worktrees, model switches, MCP elicitation, and instruction loading. Full list: hooks reference.

A hook matches on text, not intent. A PreToolUse guard that greps the Bash command string will also fire on a harmless command that merely quotes the pattern. That is the correct trade — work around a false positive by using a different tool, not by loosening the regex.

Skills

A folder with a SKILL.md. Keep the body under about 500 lines and push detail into sibling files — Claude loads them only when it needs them.

my-skill/
├── SKILL.md        # overview + navigation
├── reference.md    # loaded on demand
├── examples.md
└── scripts/helper.py

Where they live

ScopePathInvoked as
Personal~/.claude/skills/deploy/SKILL.md/deploy
Project.claude/skills/deploy/SKILL.md/deploy
Nestedapps/web/.claude/skills/deploy//apps/web:deploy
Pluginmy-plugin/skills/deploy//my-plugin:deploy

Enterprise beats personal beats project. Skills override same-named files in .claude/commands/.

Frontmatter

FieldPurpose
descriptionHow Claude decides to invoke it. The single highest-leverage field
disable-model-invocationtrue — only you can run it. For anything with side effects
user-invocablefalse — only Claude can. Background knowledge
allowed-tools / disallowed-toolsPre-approve or remove tools while active
context: forkRun the skill in an isolated subagent
agent · backgroundWhich subagent · whether to wait for its result
arguments · argument-hintNamed positional args · autocomplete hint
pathsGlobs limiting when the skill auto-loads
model · effortOverride for this skill's run

Arguments and variables

PlaceholderResolves to
$ARGUMENTSEverything passed
$0 $1 …Positional arguments
$nameA named argument from arguments:
${CLAUDE_PROJECT_DIR}Project root
${CLAUDE_SKILL_DIR}This skill's directory
${CLAUDE_PLUGIN_ROOT}Plugin install directory

Live context injection

Backtick-bang runs a shell command before Claude sees the skill, and substitutes the output. This is what turns a static template into something that reacts to the repo.

---
description: Summarize uncommitted changes and flag anything risky.
allowed-tools: Bash(git *)
---

## Current changes
!`git diff HEAD`

## Instructions
Summarize the diff in three bullets, then list the risks.

Non-zero exit aborts the invocation; there's a two-minute timeout per command; disableSkillShellExecution turns the whole mechanism off.

Subagents

Markdown with frontmatter, in .claude/agents/ or ~/.claude/agents/.

---
name: code-reviewer
description: Reviews code for quality and best practices.
tools: Read, Glob, Grep
model: sonnet
---

You are a code reviewer. Analyze the code and give specific,
actionable feedback on quality, security, and correctness.

Frontmatter

FieldPurpose
tools / disallowedToolsAllowlist / denylist
modelsonnet · opus · haiku · fable · a full ID · inherit
permissionModePer-agent permission mode
maxTurnsCap on agentic turns
skillsSkills preloaded into its context
mcpServersMCP servers available to it
memoryIts own auto memory: user · project · local
isolation: worktreeGive it its own git worktree
effort · background · colorEffort level · stay backgrounded · display color

Built in

AgentToolsFor
ExploreRead-onlySearch and discovery across many files
PlanRead-onlyResearch before presenting a plan
general-purposeEverythingMulti-step work and code changes

Invoking

# let Claude route by description — say it plainly
Use the test-runner subagent to fix the failing tests

# force a specific one
@agent-code-reviewer look at the auth changes

# run a whole session as one
claude --agent code-reviewer

Parallel is not the default. Spawning several subagents for one job per item only runs concurrently if you say so — "in parallel, one per file" — otherwise they go one at a time.

MCP servers

# HTTP, the common case
claude mcp add --transport http notion https://mcp.notion.com/mcp

# with a static token
claude mcp add --transport http github https://api.githubcopilot.com/mcp/ \
  --header "Authorization: Bearer $GITHUB_PAT"

# local process over stdio
claude mcp add --transport stdio jobs -- node mcp/jobs-server/index.js

# inspect and authenticate
claude mcp list
claude mcp login sentry

Scopes

ScopeStored inShared
local (default)~/.claude.jsonNo — this project only
project.mcp.json in the repoYes, via version control
user~/.claude.jsonNo — all your projects

.mcp.json

{
  "mcpServers": {
    "jobs": {
      "type": "stdio",
      "command": "node",
      "args": ["mcp/jobs-server/index.js"]
    },
    "api": {
      "type": "http",
      "url": "https://mcp.example.com/mcp",
      "headers": { "Authorization": "Bearer ${API_TOKEN}" },
      "timeout": 600000
    }
  }
}

${VAR} and ${VAR:-default} expand in command, args, env, url, and headers. Transports: stdio, http, sse (deprecated), ws.

Tools you allow are tools you trust. MCP permission rules take the form mcp__<server>__<tool>, and allow-globs must name a specific server: mcp__github__get_* works, a bare mcp__* allow is skipped with a warning. Allow the read tools; leave the write ones prompting.

CLAUDE.md & memory

Load order, broadest first

ScopeLocation
Managed policy/Library/Application Support/ClaudeCode/CLAUDE.md (macOS) · /etc/claude-code/CLAUDE.md (Linux)
User~/.claude/CLAUDE.md
Project./CLAUDE.md or ./.claude/CLAUDE.md
Local./CLAUDE.local.md — gitignore it

Files are concatenated, not overridden, from the filesystem root down to your working directory. Files in subdirectories load when Claude reads files there.

Rules

Split large instruction sets into .claude/rules/*.md. A rule with paths: frontmatter loads only when Claude touches matching files, which is how you keep a monorepo's context bill down.

---
paths:
  - "src/api/**/*.ts"
---

# API rules
- Every endpoint validates its input.
- Use the standard error response shape.

Practical limits

ThingLimit
CLAUDE.md lengthTarget under 200 lines. Skipped entirely above 4 MiB
Imports@path/to/file, max 4 hops deep. Backticks make a path literal
Auto memory~/.claude/projects/<project>/memory/; first 200 lines or 25KB of MEMORY.md load each session
HTML commentsStripped before injection — free notes for human maintainers

If an instruction must hold every single time, it is not a CLAUDE.md line. It is a hook.

CLAUDE.md arrives as a user message after the system prompt. Claude reads it and tries to follow it — there is no compliance guarantee, especially where two files disagree. Run /context to confirm what actually loaded, and /memory to edit it.

Keep going