cheat sheet

Claude Code Overview

Install, configure, and use Claude Code — Anthropic's agentic CLI. Covers interactive mode, headless scripting, CLAUDE.md memory files, the project/user settings hierarchy, IDE integration, and authentication.

Claude Code Overview

What it is

Claude Code is Anthropic's official agentic CLI — it embeds an AI coding assistant directly inside the terminal. It can read and edit files, run shell commands, manage git, call MCP tools, spawn subagents, and coordinate multi-step software-engineering tasks autonomously, all driven by natural-language instructions in an interactive REPL or non-interactively via --print flags inside scripts. It is the fastest way to apply Claude's reasoning to real codebases without leaving your development environment, and the primary alternative is calling the Anthropic API directly (which gives you raw model output but no tools, memory, hooks, or MCP).

Install

Claude Code ships as an npm package and installs globally. Node.js 18 or newer is required; the binary works on macOS, Linux, and Windows (native or WSL).

bash
# Global install via npm
npm install -g @anthropic-ai/claude-code

# Confirm the binary is on PATH
claude --version

Output:

text
added 1 package, and audited 1 package in 3s
found 0 vulnerabilities
1.x.x

Alternative installation methods include the official one-line installer script, a VS Code extension, a JetBrains plugin, and the browser UI at claude.ai/code. The npm package is the canonical artifact and is what every other surface ultimately runs.

bash
# One-line installer (downloads the latest binary into ~/.local/bin)
curl -fsSL https://claude.ai/install.sh | bash

Output:

text
Downloading claude-code ...
Installed to /home/alice/.local/bin/claude

Authenticate

Claude Code authenticates against the Anthropic API with a key. The key can be set in the shell environment, stored in settings.json, fetched from a secret manager via apiKeyHelper, or provided on first launch through an OAuth flow.

bash
# Shell environment (most common)
export ANTHROPIC_API_KEY="sk-ant-..."
claude --version

Output:

text
1.x.x
bash
# OAuth flow — runs once, then caches a token under ~/.claude/
claude login

Output:

text
Open this URL in your browser to authenticate:
  https://console.anthropic.com/oauth/cli?state=...
✅ Logged in as alice@example.com

For shared machines or CI, set ANTHROPIC_API_KEY in the environment and never commit it. For corporate setups using Amazon Bedrock or Google Vertex AI, set CLAUDE_CODE_USE_BEDROCK=1 or CLAUDE_CODE_USE_VERTEX=1 instead of an Anthropic key.

Launch interactive mode

The interactive REPL is the default surface — running claude with no arguments opens a TUI where you type natural-language requests and Claude reads, edits, and runs commands inside the current working directory.

bash
claude

Output:

text
╭─────────────────────────────────────────────╮
│ ✻ Welcome to Claude Code research preview!  │
│                                             │
│   /help for help, /exit to quit             │
╰─────────────────────────────────────────────╯

?  What would you like to do?

Type a request and press Enter. Claude reads the project, plans, and asks for confirmation before destructive actions.

text
> refactor the auth module to use JWT instead of session tokens

Claude will list affected files, show diffs, and request permission before writing.

Permission model

Claude Code asks before taking potentially destructive actions — file edits, shell commands, network calls. Every prompt offers three choices: allow once, allow always for this session, or deny. The "always" choice persists into the session-local allowlist and disappears when the session ends; to make a rule permanent, add it to settings.json (permissions.allow). See the Settings page for the rule grammar.

text
⚠ Claude wants to run:
    Bash: npm test

  [a] Allow once    [A] Always allow    [d] Deny

Output: (none — interactive prompt; user picks a choice)

Context window management

The context window holds the entire conversation plus any files Claude has read. As it grows it slows responses and increases cost. Use /compact to summarise prior context and continue, /clear to start fresh, and /context to see current usage.

text
> /context

Output:

text
Context window: 84,310 / 200,000 tokens used (42%)
  System + tools: 18,200
  CLAUDE.md:      4,140
  Conversation:   61,970

/compact is non-destructive — Claude keeps everything important in a condensed summary. /clear discards the whole conversation. Reach for /compact after finishing a logical unit of work and /clear when changing tasks entirely.

Headless (non-interactive) mode

Headless mode runs a single prompt to completion, prints the result to stdout, and exits with code 0 on success. It's the mode used by shell scripts, CI pipelines, pre-commit hooks, and editor integrations.

bash
claude --print "List all TODO comments in this repo"

# Short form
claude -p "What does this project do?"

Output:

text
This project is an Astro-based static site for developer cheat sheets and code snippets,
built with Tailwind CSS and deployed to Cloudflare Pages.

Pipe stdin into Claude to pass file content as additional context. Combine with --output-format json to capture structured results.

bash
cat error.log | claude -p "What is causing this error?"

Output:

text
The error is a NullPointerException at UserService.java:142. The `currentUser` field
is null when `getPreferences()` is called — likely because `authenticate()` was not
called before accessing the user object.
bash
# JSON output for scripting
claude --output-format json -p "List the exports in this file" < src/utils.ts

Output:

text
{"type":"result","result":"The file exports: formatDate, parseISO, addDays, diffDays","session_id":"sess_01...","cost_usd":0.0012}

Allowed tools flag

--allowedTools restricts which tools Claude may call during the session. Combine it with --disallowedTools for fine-grained policy. In CI use --dangerously-skip-permissions to skip all prompts — never use that flag interactively.

bash
# Read-only inspection — no edits or commands
claude --allowedTools "Read,Bash(git log:git diff:git status)" -p "Summarize recent changes"

# Allow a specific bash subcommand
claude --allowedTools "Bash(npm test)" -p "Run the tests and tell me what failed"

Output: (none — exits 0 on success)

CLAUDE.md — persistent instructions

CLAUDE.md files give Claude persistent context and standing instructions. Claude reads them automatically at the start of every session and they count toward the context window, so keep them short, structured, and skimmable.

Hierarchy

LocationScopePurpose
~/.claude/CLAUDE.mdGlobal (all projects)Personal preferences, global style rules
<project-root>/CLAUDE.mdProjectArchitecture notes, conventions, commands
<subdir>/CLAUDE.mdSubtreeComponent-specific guidance for that directory

Claude merges all applicable CLAUDE.md files (global → project → subdir) before starting. More specific files override less specific ones on conflict.

Example project CLAUDE.md

markdown
# Project: Acme API

## Stack
- FastAPI + SQLAlchemy 2.0
- Postgres 16, Alembic for migrations
- pytest + pytest-asyncio for tests

## Commands
- Run tests: `pytest tests/ -x`
- Start dev server: `uvicorn app.main:app --reload`
- Lint: `ruff check . && ruff format --check .`

## Conventions
- Use `async def` for all route handlers
- No `print()` statements — use `structlog`
- All new endpoints need a test in `tests/api/`
- Never edit `alembic/versions/` directly

## Files to avoid
- `config/secrets.yaml` — not in git; local only

Example global CLAUDE.md

markdown
# Global preferences

- Prefer concise explanations — skip restating what I already know
- Default to Python 3.12+ syntax
- Use `ruff` for formatting, not `black`
- Never add emoji to code comments

Think of CLAUDE.md as "things a new teammate would need to know in the first 30 minutes that they couldn't figure out from the code alone." Long prose slows context load — prefer bullets, tables, and code blocks.

Importing other files

CLAUDE.md supports an @path import syntax that inlines another Markdown file at session start. This is useful for splitting a large CLAUDE.md into multiple topic files.

markdown
# Acme API project notes

@./docs/architecture.md
@./docs/coding-conventions.md
@~/.claude/snippets/python-style.md

Output: (none — paths are inlined when the session loads)

IDE integration

VS Code

Install the Claude Code extension from the VS Code Marketplace. It adds an inline diff review pane, a chat panel docked to the sidebar, and a keyboard shortcut (Cmd+Esc on macOS, Ctrl+Esc on Windows/Linux) that opens Claude with the current selection or file in context.

bash
code --install-extension anthropic.claude-code

Output:

text
Installing extensions...
Extension 'anthropic.claude-code' v1.x.x was successfully installed.

JetBrains

Install Claude Code from the JetBrains Marketplace. The plugin exposes the same surfaces — chat panel, inline diff, file/selection context. Accessible via Tools → Claude Code.

Neovim

A community plugin (claude-code.nvim) wraps the CLI with a floating window and quickfix-style diff handling. Install via lazy.nvim:

lua
{
  "anthropic/claude-code.nvim",
  config = function()
    require("claude-code").setup({})
  end,
}

Output: (none — plugin loaded on next startup)

Session management

Claude Code stores conversation history under ~/.claude/projects/<project-hash>/. Each working directory hashes to its own project, so session lists are scoped to the project you are inside.

bash
# List recent sessions for the current project
claude sessions list

# Resume a previous session by ID
claude sessions resume sess_01abc...

# Delete a session
claude sessions delete sess_01abc...

# Clear all local session history
claude sessions clear

Output:

text
sess_01abc... 2026-05-24 14:02  added JWT auth
sess_01def... 2026-05-23 10:18  refactor user service
sess_01ghi... 2026-05-22 16:44  fix race condition in worker

--continue (or -c) jumps back into the most recent session for the current directory. --resume <id> (or -r) targets a specific session.

bash
claude --continue
claude --resume sess_01abc...

Output: (none — opens REPL with prior context loaded)

Useful startup flags

FlagEffect
--print / -pHeadless mode — print response and exit
--output-formattext (default), json, or stream-json
--allowedToolsComma-separated list of tools to permit
--disallowedToolsTools to always deny
--modelOverride model (e.g. claude-sonnet-4-6)
--continue / -cResume most recent session in this directory
--resume <id> / -rResume a specific session
--max-turns <n>Limit agent turns in non-interactive mode
--system-prompt <text>Replace the default system prompt
--append-system-prompt <text>Add text to the system prompt
--mcp-config <path>Load an MCP server config file
--add-dir <path>Extend filesystem access beyond cwd
--no-auto-compactDisable automatic context compaction
--dangerously-skip-permissionsSkip all permission prompts (CI only)
--verbose / --debugVerbose logging including tool calls

See CLI Reference for the complete flag set with examples.

Configuration file locations

Claude Code reads configuration from a hierarchy of files. Project-scoped settings override user-global settings, and a git-ignored local file overrides both.

FileScopeDescription
~/.claude/settings.jsonUser-globalGlobal personal defaults
.claude/settings.jsonProjectTeam defaults — commit to git
.claude/settings.local.jsonProject (gitignored)Personal overrides
~/.claude/CLAUDE.mdUser-globalGlobal memory
<project>/CLAUDE.mdProjectProject memory
.claude/commands/*.mdProjectCustom slash commands
~/.claude/commands/*.mdUser-globalPersonal slash commands
.claude/skills/<name>/SKILL.mdProjectCustom skills
~/.claude/skills/<name>/SKILL.mdUser-globalPersonal skills
bash
# Show the merged settings as Claude sees them
claude /config

Output: (none — opens the active settings.json in $EDITOR)

Common pitfalls

  1. Missing API key — if ANTHROPIC_API_KEY is not set and no apiKeyHelper is configured, claude exits with an auth error on startup; set the key in your shell profile or run claude login.
  2. Switching directories mid-task — session history is keyed by the working directory hash; running cd and then claude --continue does not resume the previous session because the project hash changed.
  3. CLAUDE.md too long — prose-heavy CLAUDE.md files inflate the system prompt and slow every turn; trim ruthlessly and use @imports to lazy-load detail only where it matters.
  4. --dangerously-skip-permissions in interactive use — never use this flag at a human terminal; it disables every safety prompt, including network and destructive shell calls.
  5. Permission rules forgotten when project-scope changessettings.local.json is gitignored, so personal allow-lists do not move with the repository; new contributors hit prompts that look "wrong" to them.
  6. Stale sessions consuming context budget~/.claude/projects/<hash>/ grows over time; periodically run claude sessions clear or set cleanupPeriodDays in settings.json.

Real-world recipes

First-run checklist

Set up Claude Code from scratch on a new machine in a few minutes.

bash
# 1. Install
npm install -g @anthropic-ai/claude-code

# 2. Authenticate (one-time)
export ANTHROPIC_API_KEY="sk-ant-..."

# 3. Verify
claude --version
claude /doctor

# 4. Create a project CLAUDE.md
cd ~/Code/myproject
echo "# Project: myproject" > CLAUDE.md
echo "## Commands" >> CLAUDE.md
echo "- Test: pnpm test" >> CLAUDE.md

# 5. Start a session
claude

Output:

text
✅ API key found
✅ Node.js 22.4.0
✅ @anthropic-ai/claude-code 1.x.x
✅ API connectivity: OK
1.x.x

Pipeline: review then auto-fix

Use headless mode to chain a review pass into a fix pass, gated by exit code.

bash
# Step 1: review the diff into a JSON report
git diff origin/main...HEAD \
  | claude -p "Output JSON: {issues: [{file, line, severity, fix}]}" \
           --output-format json \
  > /tmp/review.json

# Step 2: if any critical issues, apply fixes
if jq -e '[.result | fromjson | .issues[] | select(.severity == "critical")] | length > 0' /tmp/review.json; then
  claude -p "Apply the fixes described in /tmp/review.json"
fi

Output:

text
Applied 3 fixes:
  - src/auth.py:42 — parameterized SQL query
  - src/api/users.py:88 — added null-check
  - src/utils/format.py:14 — replaced eval() with json.loads()

Switch model mid-session

Switch from a fast model to a stronger one when the task gets hard, without restarting the session.

text
> /model claude-opus-4-7

Output:

text
Active model is now claude-opus-4-7.

Multi-directory workspace

Open Claude with access to multiple project roots — useful when refactoring shared code across sibling repos.

bash
cd ~/Code/frontend
claude --add-dir ~/Code/backend --add-dir ~/Code/shared

Output: (none — opens REPL with extended filesystem scope)

Force headless and exit codes

CI pipelines want a clean exit code that reflects task success. Combine --output-format json with jq to map results to exit codes.

bash
RESULT=$(claude -p "Lint and report errors as JSON. {errors: []}" \
  --output-format json --allowedTools "Read,Bash(ruff check)")
ERRORS=$(echo "$RESULT" | jq -r '.result' | jq '.errors | length')
[ "$ERRORS" -gt 0 ] && exit 1 || exit 0

Output:

text
0