TL;DR: Claude Code is Anthropic's terminal-based AI coding tool. This cheat sheet covers every major feature category: installation and auth, core commands, context operators (@file, @folder, @codebase, @web), slash commands (/help, /clear, /cost, /config, /doctor), permission modes, keyboard shortcuts, CLAUDE.md setup, and advanced features like MCP servers, channels, headless mode, and --print. Bookmark this page and use it as a running reference.

Getting Started: Install, Auth, Init

If you haven't set up Claude Code yet — or you're setting it up on a new machine — here's the full sequence. Three commands and you're running.

Installation

Claude Code is a Node.js package distributed via npm. You need Node.js 18+ installed first. If you don't have it, grab it from nodejs.org (the LTS version is fine).

# Install Claude Code globally
npm install -g @anthropic-ai/claude-code

# Verify installation
claude --version

When to reinstall: If Claude Code behaves strangely or is missing features you've seen mentioned, run npm install -g @anthropic-ai/claude-code again to pull the latest version. Updates ship frequently.

Authentication

Claude Code connects to the Anthropic API. You need an API key from your Anthropic console. The first time you run claude, it'll walk you through auth — but here's what's happening:

# First run triggers auth automatically
claude

# Or set your API key as an environment variable
export ANTHROPIC_API_KEY=sk-ant-...

Pro tip: Put the export line in your ~/.zshrc or ~/.bashrc file so your API key loads automatically in every terminal session. You'll never have to set it again.

Initializing in a Project

You can run claude from any directory and it works. But running /init inside a session (or starting in a project directory) helps Claude Code build a mental map of your project:

# Navigate to your project first
cd my-project

# Start Claude Code
claude

# Inside the session, kick off project analysis
/init

/init scans your project structure and offers to create a CLAUDE.md file — a persistent instruction file Claude reads at the start of every session. More on that in the CLAUDE.md section below.

When to use /init: On any new project, or when you're joining an existing codebase you haven't worked with in Claude before. It saves you from re-explaining your stack every session.

Core Commands

These are the terminal commands you run to start and control Claude Code sessions. Most of the time you'll just type claude — but knowing the flags gives you significantly more control.

Starting a Session

# Start interactive session in current directory
claude

# Start with an initial message (skip the blank prompt)
claude "explain the structure of this project"

# Start in a specific directory
claude --dir /path/to/project

# Start and immediately run a command non-interactively
claude --print "what does this repo do?"
# Short form:
claude -p "what does this repo do?"

--print / -p: This is the headless mode flag. Claude answers your question, prints to stdout, and exits. No interactive session. Essential for scripts and automation. See the Advanced Features section for more on this.

Model Selection

# Use a specific model
claude --model claude-opus-4-6

# Use Haiku for fast, cheap tasks
claude --model claude-haiku-4-5-20251001

# List available models
claude /models

When to switch models: The default is usually Claude Sonnet, which balances speed and capability well. Switch to Opus for complex architectural decisions or deeply nuanced code review. Switch to Haiku when you're doing simple repetitive tasks (renaming variables, writing boilerplate) and want to cut costs.

Continuing Previous Sessions

# Resume the most recent session
claude --continue

# Resume and add a new message immediately
claude --continue "now add error handling to what we built"

# Resume a specific session by ID
claude --resume <session-id>

When to use --continue: If you closed your terminal mid-build and want to pick up exactly where you left off without re-explaining context. Claude picks up the entire prior conversation.

Context Operators: @file, @folder, @codebase, @web

Context operators are how you pull information into Claude's active context mid-conversation. Type them directly in the chat input. They're one of the most underused features in Claude Code — most people just paste code manually when they could be using these.

@file — Load a Specific File

@src/components/Button.tsx
@package.json
@.env.example

Loads the entire content of the specified file into the current message context. Claude reads it as if you'd pasted it.

When to use: When you know exactly which file is relevant. "Look at @src/auth/middleware.js — why does the token validation fail for expired tokens?" is faster and cleaner than copy-pasting the file content.

@folder — Load a Directory

@src/components/
@lib/utils/

Loads all files from a folder (non-recursively by default) into context at once. Useful when a feature lives across multiple files in one directory.

When to use: "Here's the entire components folder @src/components/ — which ones are re-rendering unnecessarily?" You're giving Claude the full picture of a module without loading the whole codebase.

@codebase — Semantic Search Across Your Project

How does authentication work in this project? @codebase
Where is the payment processing logic? @codebase

Triggers a semantic search across your entire project and automatically pulls in the most relevant files. Claude finds what you need — you don't have to know which files to load.

When to use: When your question spans multiple files or you don't know where the relevant code lives. It's slower than @file because it has to search, but far more powerful when you're exploring or debugging something unfamiliar.

@file vs. @codebase in plain terms: @file is "I know exactly where this is, load it." @codebase is "I don't know where this is, find it for me." Use @file when you're working on a specific thing. Use @codebase when you're investigating or asking a broad question about how something works.

@web — Fetch Live Web Content

What changed in React 19? @web https://react.dev/blog/...
Check the latest Stripe API docs @web https://stripe.com/docs/api

Fetches the content of a URL and adds it to context. Claude reads the live page, not its training data snapshot.

When to use: For anything where the docs may have changed since Claude's training cutoff — library updates, API changes, new framework features. Don't rely on Claude's memory for anything that ships fast. Pull the actual docs in with @web.

Slash Commands

Slash commands are typed directly in the Claude Code chat input. They're control commands — they manage the session, not the project. Here's every one worth knowing.

Session Management

/help          # Show all available commands
/clear         # Clear conversation history (starts fresh)
/compact       # Summarize history to save context space
/exit          # Exit the session (also: Ctrl+C or Ctrl+D)

/clear vs. /compact: /clear wipes the entire conversation history. Use it when you're starting a completely different task and don't want the old context confusing Claude. /compact is smarter — it summarizes the conversation so far into a compressed memory, preserving the important context without burning through your token budget. Use /compact when a session is getting long but you're still working on the same thing.

Cost and Usage

/cost          # Show token usage and estimated cost for this session
/usage         # Detailed breakdown of API calls made

When to use /cost: Run it before starting a long agentic task so you have a baseline, then check it afterward. It's also useful for building intuition about which types of requests are expensive — loading large files, using @codebase, calling Opus models.

Configuration

/config        # View and edit Claude Code settings
/model         # Switch model mid-session
/models        # List all available models

What /config shows: Your current permission mode, allowed/blocked tools, active model, API key status, and any project-level overrides. Think of it as the settings panel for the current session.

Diagnostics

/doctor        # Run a health check on your Claude Code setup
/status        # Show current session status and context usage

When to use /doctor: When something feels off — Claude isn't reading your CLAUDE.md, tool calls are failing, or you're getting unexpected permission errors. It diagnoses common setup problems and tells you what's wrong.

Project and Memory

/init          # Scan project and optionally create CLAUDE.md
/memory        # View what Claude has stored in memory for this project
/forget        # Remove a specific memory item

/memory and /forget: Claude Code can store persistent project memories beyond what's in CLAUDE.md — things you've told it during sessions. /memory shows you what it's retained. /forget lets you delete specific items if they're wrong or outdated.

Tools and Permissions

/tools         # List all tools Claude has access to
/permissions   # View current permission settings
/allowed-tools # Show which tools are enabled

These are most useful when you're debugging why Claude can't do something — like run a terminal command or access the network. If a tool you expect to be available isn't listed, you'll need to enable it in your permission settings.

Permission Modes

Permission modes control how much Claude Code can do autonomously without asking you first. This is one of the most important things to understand — getting it wrong means either constant interruptions or Claude running wild.

The Three Modes

Default (ask) mode: Claude asks for permission before every significant action — editing files, running commands, accessing the network. This is the safest mode and the default when you first start. Good for getting familiar with what Claude is doing, or when working on production code you want to review carefully.

Auto-edit mode: Claude can edit files without asking, but still asks before running terminal commands and network operations. This is the sweet spot for most solo projects — you get fast file changes without Claude executing arbitrary shell commands unsupervised.

--dangerously-skip-permissions: Claude does everything without asking. Edits files, runs commands, accesses the network. Use with caution — and only on projects where you've reviewed the CLAUDE.md and know what Claude is allowed to do.

# Start in default ask mode (default — no flag needed)
claude

# Allow file edits without asking, but ask for commands
claude --auto-edit

# Skip all permission prompts (use carefully)
claude --dangerously-skip-permissions

Fine-Grained Permission Rules

You can also set specific allow rules rather than using a broad mode. This is the most professional approach — let Claude freely edit files in your source directory, but require approval for anything that touches the database or runs deployments:

# In your settings or CLAUDE.md, you can specify:
# Allow: edit files in src/, run npm test
# Ask: anything involving git push, database migrations, deployment scripts

Configure these in /config or in your ~/.claude/settings.json file. The granular approach means you're not choosing between "ask every time" and "full autopilot" — you define the boundaries that make sense for your project.

Practical rule of thumb: For personal projects where you're the only developer — auto-edit is probably fine for day-to-day work. For anything with real users, real data, or a deployment pipeline — stick to default ask mode or use fine-grained rules. The few extra seconds per approval are worth it when Claude misunderstands a task.

Keyboard Shortcuts

These work inside the active Claude Code session (the interactive REPL). They're all standard terminal shortcuts, but knowing them cuts friction significantly in long sessions.

Input and Navigation

Shortcut What it does
Enter Send message
Shift+Enter Insert a newline without sending (for multi-line prompts)
Up Arrow Recall previous message (cycle through history)
Ctrl+C Stop current response mid-stream
Ctrl+C (twice) Exit the session
Ctrl+D Exit the session (EOF signal)
Ctrl+L Clear the terminal display (does not clear conversation history)
Ctrl+Z Suspend session (resume with fg)

Approval Prompts

When Claude asks for permission to take an action, these are your response keys:

Key What it means
y / Enter Yes, allow this action once
n No, skip this action
a Allow all similar actions for this session
d Deny all similar actions for this session
e Edit the command before running it

The "a" key is underused. If you're doing a big refactor and Claude needs to edit 20 files, hitting "y" 20 times is miserable. Hit "a" on the first one and let it run. You can always review the diff afterward.

CLAUDE.md Configuration

CLAUDE.md is the single highest-leverage thing you can add to any project you use Claude Code on. It's a plain markdown file that Claude reads automatically at the start of every session. No re-explaining your stack. No repeating your conventions. It just knows.

For a deep dive, read our full guide on what a CLAUDE.md file is and how to write one. Here's the quick-reference version.

Where to Put It

# Project root — same level as package.json, README.md, .git/
/my-project/
  CLAUDE.md        ← Claude reads this at session start
  package.json
  src/
  ...

# You can also have subdirectory CLAUDE.md files
# for directory-specific instructions
/my-project/src/CLAUDE.md     ← Claude reads this when working in src/

What to Put In It

# Project Name
Brief description of what this project is.

## Tech Stack
- Runtime: Node.js 20
- Framework: Next.js 14 (App Router)
- Database: PostgreSQL via Prisma
- Styling: Tailwind CSS
- Deployment: Vercel

## Common Commands
- `npm run dev` — start local dev server on port 3000
- `npm run build` — production build
- `npm run test` — run Vitest unit tests
- `npx prisma migrate dev` — run pending DB migrations

## Code Conventions
- Use TypeScript strictly (no `any`)
- Functional components only, no class components
- Server components by default; use `"use client"` only when needed
- Errors: always use the `AppError` class from `lib/errors.ts`

## Architecture Notes
- Auth is handled by Clerk — do not roll custom auth
- All DB calls go through service layer in `lib/services/`
- API routes live in `app/api/` and must validate with Zod

## Do Not
- Do not run `prisma db push` — always use migrate dev
- Do not commit .env files
- Do not use `console.log` in production code — use the logger in `lib/logger.ts`

Length guidance: 200–500 lines is plenty. Long CLAUDE.md files dilute attention — Claude can't focus on everything equally. Be specific about the things that actually matter for daily work, not a complete architecture manifesto.

Creating It with /init

# Run this inside a Claude Code session to auto-generate CLAUDE.md
/init

Claude will scan your project and propose a CLAUDE.md draft. It's a good starting point — then edit it to add the "do not" rules, the non-obvious conventions, and the context that isn't derivable from the file structure alone.

Advanced Features

Headless Mode and --print

The --print flag (short: -p) runs Claude non-interactively. It takes a prompt, returns a response, and exits. This is the flag that makes Claude Code scriptable.

# Ask a question, get a response, exit
claude --print "summarize what this repo does"

# Pipe output from another command into Claude
git diff HEAD~1 | claude -p "write a commit message for this diff"

# Use in a shell script
SUMMARY=$(claude -p "explain this function: $(cat src/utils.js)")
echo "$SUMMARY" > docs/utils-explanation.md

# Chain with other tools
claude -p "convert this JSON to a markdown table" < data.json | pbcopy

When to use headless mode: Automating code reviews on PRs, generating documentation from source files, summarizing logs, converting files, running as part of a build step. Any time you want Claude's output to feed into something else rather than a conversation.

MCP Servers

MCP (Model Context Protocol) servers extend what Claude Code can connect to — databases, APIs, internal tools, browsers, file systems. Think of them as plugins that give Claude access to things it can't reach by default.

# Add an MCP server to your configuration
claude mcp add <server-name> <command>

# Example: add a Postgres MCP server
claude mcp add postgres npx @modelcontextprotocol/server-postgres postgresql://localhost/mydb

# List active MCP servers
claude mcp list

# Remove an MCP server
claude mcp remove <server-name>

Common MCP use cases:

  • Database access — Let Claude query your dev database directly instead of you pasting schema and sample data
  • Browser control — Claude can open pages, click things, and scrape content through a browser MCP
  • Internal APIs — Connect Claude to internal tooling your team uses
  • File systems — Access directories outside your project root

For a full explainer on the protocol, read our guide on what an MCP server is and how it works.

Claude Code Channels

Channels let you run multiple isolated Claude Code sessions — each with its own conversation history, context, and permissions. Useful when you're working on separate features simultaneously, or when you want to keep a "planning" session separate from a "building" session.

# Start a named channel
claude --channel feature-auth

# Start another channel in a different terminal
claude --channel feature-payments

# List all active channels
claude channels list

# Switch to a specific channel
claude --channel feature-auth --continue

Each channel maintains its own memory and conversation history. Switching channels is like switching browser tabs — your other work is still there when you come back.

For more detail on how channels work and when they're worth setting up, see our full article on Claude Code channels.

Running as an Agent (Agentic Mode)

Claude Code can run autonomously on multi-step tasks — not just answering a question, but executing a full plan: reading files, writing code, running tests, fixing failures, and iterating.

# Describe a multi-step task; Claude plans and executes
claude "add a forgot-password flow to the auth system. use the existing email service in lib/email.ts, add a reset token to the User model, create the API route, and wire up the UI component"

# Headless agentic run for automation
claude --print --dangerously-skip-permissions "run the test suite and fix any failing tests"

When to use agentic mode: For tasks where you can clearly describe the outcome but don't want to babysit each step. Works best when:

  • The task is well-defined with a clear end state
  • You have tests that confirm correctness
  • The codebase has a CLAUDE.md with clear conventions (so Claude doesn't invent its own)
  • You're comfortable reviewing a diff at the end rather than watching each edit

Settings Files

Claude Code uses two settings files for persistent configuration:

# Global settings (applies to all projects)
~/.claude/settings.json

# Project-level settings (checked into repo, shared with team)
.claude/settings.json

# Local overrides (not checked in — your personal tweaks)
.claude/settings.local.json

The settings cascade: global → project → local. Project settings override global. Local settings override project. This means your team can share a .claude/settings.json with agreed-upon defaults, and you can override specific things in your local file without touching the shared config.

// Example .claude/settings.json
{
  "permissions": {
    "allow": [
      "Edit(*)",
      "Bash(npm test)",
      "Bash(npm run lint)"
    ],
    "deny": [
      "Bash(git push*)",
      "Bash(npm publish*)"
    ]
  }
}

Environment Variables

# Core
ANTHROPIC_API_KEY=sk-ant-...       # Required API key
CLAUDE_MODEL=claude-sonnet-4-6     # Default model

# Behavior
CLAUDE_SKIP_PERMISSIONS=true       # Auto-approve all (same as --dangerously-skip-permissions)
CLAUDE_AUTO_COMPACT=true           # Automatically compact long sessions

# Debug
CLAUDE_DEBUG=true                  # Verbose logging
ANTHROPIC_LOG=debug                # Full API request/response logging

Set these in your shell profile or in a .env file in your project (don't commit the API key).

Quick Reference Card

Everything that matters, condensed. Print this, screenshot it, keep it somewhere obvious.

Terminal Commands

claude                         # Start interactive session
claude "message"               # Start with initial message
claude -p "message"            # Headless / non-interactive
claude --continue              # Resume last session
claude --model claude-opus-4-6 # Choose model
claude --auto-edit             # Skip file edit confirmations
claude --dangerously-skip-permissions  # Skip all confirmations

Slash Commands (in session)

/help       # All commands
/clear      # Wipe conversation history
/compact    # Compress history, save context
/cost       # Show token usage + cost
/config     # View/edit settings
/doctor     # Diagnose setup issues
/init       # Scan project, create CLAUDE.md
/memory     # View stored memory
/model      # Change model mid-session

Context Operators (in chat input)

@filename.js          # Load specific file
@src/components/      # Load folder contents
@codebase             # Semantic search, load relevant files
@web https://...      # Fetch live URL content

Permission Approval Keys

y / Enter   # Approve once
n           # Deny
a           # Approve all similar (this session)
d           # Deny all similar (this session)
e           # Edit before running
  • Claude Code Beginner's Guide — Start here if you're new to Claude Code. Covers installation, first session, and the mental model for how to work with it effectively.
  • What Is a CLAUDE.md File? — The full guide to writing a CLAUDE.md that actually makes a difference. Includes templates and examples for different project types.
  • What Are Claude Code Channels? — A deeper look at channels — how they work, when to use them, and how to organize multi-channel workflows for complex projects.
  • What Is an MCP Server? — The full explanation of the Model Context Protocol and how to use MCP servers to extend what Claude Code can access.

Frequently Asked Questions

What is the difference between claude and claude --print in the terminal?

Running claude opens the full interactive REPL where you have a back-and-forth conversation. Running claude --print "your prompt" (or -p for short) sends a single message, prints the response to stdout, and exits immediately. The --print flag is designed for scripting and automation — piping Claude's output into other tools, using it in shell scripts, or running it non-interactively in CI/CD pipelines. If you just want to chat or build something, use the plain claude command.

How do I stop Claude Code from asking permission every single time it edits a file?

Use auto-edit mode by running claude --auto-edit, or configure specific allow rules in your .claude/settings.json. The safest approach for everyday use is to set explicit allow rules — for example, allow editing files in your src/ directory without asking, while still requiring approval for running shell commands. This gives you speed without full permission bypass. Avoid --dangerously-skip-permissions for daily use — save that for clearly scoped automation tasks.

What does @codebase do in Claude Code and when should I use it?

@codebase triggers a semantic search across your entire project and automatically finds the most relevant files for your question, then adds them to context. Use it when you're asking something that spans multiple files — like "why does the auth flow work this way?" or "where is this function called?". It's slower than @file (which loads a specific file instantly) but much more useful when you don't know which files are relevant. Think of @file as "I know exactly where this is" and @codebase as "find it for me."

What is CLAUDE.md and do I actually need one?

CLAUDE.md is a plain markdown file you put in your project root. Claude Code reads it automatically at the start of every session and treats it as standing instructions — your tech stack, coding conventions, architecture decisions, commands to know about. You don't need one to use Claude Code, but you'll notice the difference immediately when you add one. Without it, you spend the first few messages of every session re-explaining your project. With it, Claude already knows the context and starts contributing faster. For any project you work on more than once, a CLAUDE.md file is worth the 20 minutes it takes to write.

Can I use Claude Code without an internet connection?

No. Claude Code requires an internet connection because it sends your messages to Anthropic's API and receives responses from Claude models running in the cloud. There is no fully local or offline mode. If offline AI coding is a hard requirement, you'd need a different setup — like running a local model through Ollama with a compatible interface. Claude Code is a cloud-connected tool by design.