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.
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
| Command | What it does |
|---|---|
claude | Start 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 -c | Continue the most recent conversation in this directory |
claude -r "<id|name>" "…" | Resume a specific session |
claude update | Update to the latest version |
claude doctor | Read-only install and settings diagnostics |
Config & extensions
| Command | What it does |
|---|---|
claude mcp | Configure MCP servers — see §11 |
claude mcp login <name> | Run a server's OAuth flow |
claude plugin | Manage 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|status | Account authentication |
claude setup-token | Long-lived OAuth token for CI and scripts |
Background & remote sessions
| Command | What it does |
|---|---|
claude agents | Agent 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|stop | Inspect or stop the background-session supervisor |
claude remote-control | Drive this Claude Code from claude.ai |
CLI flags
There are well over eighty. These are the ones that earn their keep.
Scope and permission
| Flag | Effect |
|---|---|
--add-dir | Give Claude extra working directories |
--permission-mode | Start in plan, acceptEdits, auto, dontAsk… |
--allowedTools / --disallowedTools | Session-scoped allow and deny rules |
--dangerously-skip-permissions | Skip prompts. Containers and VMs only |
--settings | Path to a settings file, or inline JSON |
--setting-sources | Which setting layers to load, e.g. user,project |
Model and effort
| Flag | Effect |
|---|---|
--model | Set the session model |
--fallback-model | Fall back when the primary is overloaded — sonnet,haiku |
--effort | low · medium · high · xhigh · max |
--autocompact <auto|tokens> | Set the auto-compact window, e.g. 500k |
Scripting and automation
| Flag | Effect |
|---|---|
--output-format | text, json, or stream-json |
--json-schema | Validated JSON output matching a schema you supply |
--max-turns | Cap agentic turns |
--max-budget-usd | Hard spend ceiling for the run |
--append-system-prompt | Append to the system prompt (--system-prompt replaces it) |
--agents | Define subagents inline as JSON, session-only |
--mcp-config / --strict-mcp-config | Load MCP servers from a file; ignore all others |
--bare | Skip auto-discovery of hooks, skills, and custom commands |
--safe-mode | Start 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
| Command | What it does |
|---|---|
/context | Visualize 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 |
/rewind | Roll code and conversation back to a checkpoint |
/resume | Return 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 · /cost | Token usage and cost for this session |
/export [file] | Export the conversation as plain text |
Configuration
| Command | What it does |
|---|---|
/config · /settings | Settings UI — theme, model, output style |
/permissions | View and edit allow / ask / deny rules, with their source file |
/hooks | View hook configuration for tool events |
/mcp | MCP connections and OAuth |
/skills | Manage custom and bundled skills |
/plugin | Install and manage plugins |
/memory | Edit CLAUDE.md files, toggle auto memory |
/model · /effort · /fast | Model, effort level, fast mode |
/keybindings | Open your keyboard shortcuts file |
/add-dir · /cd | Add a working directory · move the session |
Work
| Command | What it does |
|---|---|
/init | Generate a starting CLAUDE.md from the codebase |
/plan [description] | Enter plan mode straight from the prompt |
/code-review · /review | Review the diff, a PR number, a branch, or a path. Takes an effort level, plus --fix and --comment |
/security-review | Check the diff for security vulnerabilities |
/simplify | Cleanup pass — reuse, simplification, efficiency. No bug hunting |
/diff | Review the working tree, Claude's edits included |
/subtask | Hand 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 |
/worktree | Git worktrees for isolated changes |
/todos · /goal | Task list · keep working until a condition is met |
Diagnostics
| Command | What it does |
|---|---|
/doctor | Setup checkup that diagnoses and can fix issues |
/debug [description] | Turn on debug logging and troubleshoot |
/status | Current session status |
/insights | HTML report analyzing your recent local sessions |
/skill-doctor | Find unused skills and what they cost in context |
/fewer-permission-prompts | Mine transcripts for safe read-only calls, propose an allowlist |
Keyboard shortcuts
Control
| Key | Action |
|---|---|
Esc | Interrupt Claude, or close a dialog |
Esc Esc | Clear the input draft, or rewind |
Ctrl+C | Interrupt; if nothing runs, clear input, then exit on a second press |
Ctrl+D | Exit the session |
Shift+Tab | Cycle permission modes |
Ctrl+O | Toggle the transcript viewer |
Ctrl+T | Toggle Claude's task checklist |
Ctrl+B | Background the running task |
Ctrl+R | Reverse-search command history |
Ctrl+G | Open the prompt in your editor |
Ctrl+S | Stash or restore the prompt |
Ctrl+V | Paste an image from the clipboard |
Ctrl+X Ctrl+K | Stop all background subagents. Twice within 3s to confirm |
Option/Alt+P | Switch model |
Option/Alt+T | Toggle extended thinking |
Option/Alt+O | Toggle fast mode |
? on empty input | Toggle the shortcut help panel |
Prompt prefixes
| Prefix | Meaning |
|---|---|
/ | 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
| Key | Action |
|---|---|
Ctrl+A / Ctrl+E | Start / end of line |
Ctrl+K / Ctrl+U | Delete to end / to start of line |
Ctrl+W | Delete back to previous whitespace |
Ctrl+Y | Paste deleted text (Alt+Y cycles paste history) |
Alt+B / Alt+F | Back / 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
| # | Layer | File | Who it's for |
|---|---|---|---|
| 1 | Managed | managed-settings.json, MDM, console | Your organization |
| 2 | Command line | claude --settings | You, this session |
| 3 | Project local | .claude/settings.local.json | You, this project |
| 4 | Shared project | .claude/settings.json | Everyone in the project |
| 5 | User | ~/.claude/settings.json | You, every project |
A key set higher wins. Lists — permission rules, claudeMdExcludes — merge across layers rather than overriding.
Keys worth knowing
| Key | What it controls |
|---|---|
permissions | allow / ask / deny rules and the starting mode |
hooks | Your commands at lifecycle events |
env | Environment variables for every session and subprocess |
model · fallbackModel · availableModels | Default model, backups, and the allowed list |
effortLevel · modelSettings | Default effort; saved per-model effort |
sandbox.enabled | Isolate Bash from filesystem and network (macOS, Linux, WSL2) |
autoCompactEnabled · autoCompactWindow | Compaction behavior |
autoMemoryEnabled · autoMemoryDirectory | Auto memory on/off and where it's stored |
claudeMd · claudeMdExcludes | Inject org-wide instructions · skip specific CLAUDE.md files |
disableBundledSkills · skillOverrides | Turn bundled skills off, or hide individual ones |
disableAllHooks | Kill hooks, status line, and custom file suggestions at once |
attribution | Customize or hide commit and PR attribution |
statusLine | Render your own status line below the prompt |
editorMode | vim for vim bindings in the prompt |
cleanupPeriodDays | How long transcripts are kept |
outputStyle · language | Claude's role and tone · response language |
fileCheckpointingEnabled | The file snapshots /rewind restores |
strictPluginOnlyCustomization | Lock 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
| Mode | Behavior |
|---|---|
default | Manual. Prompts on first use of each tool |
acceptEdits | Auto-accepts file edits and common filesystem commands in the working directory |
plan | Reads and explores, doesn't edit source |
auto | Auto-approves with a background classifier checking each action against your request |
dontAsk | Auto-denies anything not pre-approved |
bypassPermissions | Skips 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
| Rule | Matches | Doesn't match |
|---|---|---|
Bash(npm run build) | npm run build | npm run build --watch |
Bash(npm run *) | npm run test --watch, bare npm run | npm install |
Bash(git * main) | git push origin main — every subcommand | git log |
Bash(ls *) | ls -la, ls | lsof |
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
| Code | Meaning |
|---|---|
0 | Success. stdout is parsed as JSON for a structured decision |
2 | Block. On PreToolUse the call never runs and your stderr goes back to the model |
| other | Non-blocking error. Work continues |
The events you'll actually use
| Event | Fires | Matcher | Blocks? |
|---|---|---|---|
SessionStart | Session begins or resumes | startup · resume · clear · compact · fork | No |
UserPromptSubmit | You submit a prompt | — | Yes |
PreToolUse | Before a tool runs | Tool name, regex | Yes |
PostToolUse | After a tool succeeds | Tool name | No |
PostToolUseFailure | After a tool fails | Tool name | No |
PermissionRequest | A call needs a decision | Tool name | Via JSON |
SubagentStart / SubagentStop | Subagent spawns / finishes | Agent type | Stop: yes |
Stop | Claude finishes responding | — | Yes |
PreCompact / PostCompact | Around compaction | manual · auto | No |
Notification | A notification is sent | Notification type | No |
SessionEnd | Session terminates | clear · 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
| Scope | Path | Invoked as |
|---|---|---|
| Personal | ~/.claude/skills/deploy/SKILL.md | /deploy |
| Project | .claude/skills/deploy/SKILL.md | /deploy |
| Nested | apps/web/.claude/skills/deploy/ | /apps/web:deploy |
| Plugin | my-plugin/skills/deploy/ | /my-plugin:deploy |
Enterprise beats personal beats project. Skills override same-named files in .claude/commands/.
Frontmatter
| Field | Purpose |
|---|---|
description | How Claude decides to invoke it. The single highest-leverage field |
disable-model-invocation | true — only you can run it. For anything with side effects |
user-invocable | false — only Claude can. Background knowledge |
allowed-tools / disallowed-tools | Pre-approve or remove tools while active |
context: fork | Run the skill in an isolated subagent |
agent · background | Which subagent · whether to wait for its result |
arguments · argument-hint | Named positional args · autocomplete hint |
paths | Globs limiting when the skill auto-loads |
model · effort | Override for this skill's run |
Arguments and variables
| Placeholder | Resolves to |
|---|---|
$ARGUMENTS | Everything passed |
$0 $1 … | Positional arguments |
$name | A 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
| Field | Purpose |
|---|---|
tools / disallowedTools | Allowlist / denylist |
model | sonnet · opus · haiku · fable · a full ID · inherit |
permissionMode | Per-agent permission mode |
maxTurns | Cap on agentic turns |
skills | Skills preloaded into its context |
mcpServers | MCP servers available to it |
memory | Its own auto memory: user · project · local |
isolation: worktree | Give it its own git worktree |
effort · background · color | Effort level · stay backgrounded · display color |
Built in
| Agent | Tools | For |
|---|---|---|
Explore | Read-only | Search and discovery across many files |
Plan | Read-only | Research before presenting a plan |
general-purpose | Everything | Multi-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
| Scope | Stored in | Shared |
|---|---|---|
local (default) | ~/.claude.json | No — this project only |
project | .mcp.json in the repo | Yes, via version control |
user | ~/.claude.json | No — 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
| Scope | Location |
|---|---|
| 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
| Thing | Limit |
|---|---|
| CLAUDE.md length | Target 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 comments | Stripped 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.








