I have been using Claude Code every day for over a year to build infrastructure, write Terraform, debug Kubernetes manifests, and ship production code faster than I ever thought possible. This is the guide I wish existed when I started -- not the sanitized official docs, but the real-world walkthrough that covers every gotcha, every platform quirk, and every trick I have learned the hard way.
The official docs tell you the commands. This guide tells you what actually happens, what goes wrong, and what to do about it.
By the end you will have Claude Code installed, authenticated, configured, and productive. Whether you are on macOS or Windows, a beginner or a senior engineer, this guide has you covered.
Table of Contents
- Who Is This For?
- What Is Claude Code?
- Prerequisites
- Choose Your Plan (And What They Don't Tell You About Costs)
- Install on macOS
- Install on Windows
- Authenticate
- Your First Real Session
- Set Up CLAUDE.md
- Choose Your Model
- Understand Permission Modes
- Configure Settings
- Set Up MCP Servers
- Set Up Hooks
- Master Session Management
- Use Subagents for Complex Work
- Headless Mode for CI/CD
- Editor Integrations
- Every Command You Need
- Real-World Gotchas (From 24,000+ GitHub Issues)
- Troubleshooting
- Uninstalling
Who Is This For?
- First-time users who have never touched Claude Code
- Engineers switching from GitHub Copilot or other AI coding tools
- Windows users who have been told "just use a Mac" one too many times
- Team leads evaluating Claude Code for their organization
- Anyone who tried the official quickstart and got stuck
What Is Claude Code, Actually?
Claude Code is not a chatbot with a code plugin. It is a full AI coding agent that lives in your terminal. It can:
- Read your entire codebase automatically -- no manual context loading
- Write, edit, and create files across your project
- Run shell commands (build, test, deploy) with your permission
- Use Git conversationally -- commits, branches, PRs, conflict resolution
- Debug errors by reading stack traces and tracing through your code
- Refactor at scale -- rename across files, extract modules, restructure directories
- Connect to external tools via MCP servers -- databases, GitHub, Sentry, Slack, and hundreds more
- Run autonomously in CI/CD pipelines for automated code reviews, fixes, and deployments
- Paste in screenshots and it will analyze UI, generate CSS, or debug visual bugs
Ask it "why is the build failing?" and it will read your error output, trace the source, and fix it. That is fundamentally different from autocomplete.
Prerequisites
Before installing anything, make sure your system is ready.
| Requirement | Details |
|---|---|
| macOS | 13.0 (Ventura) or later |
| Windows | 10 version 1809+ or Server 2019+ |
| Linux/WSL | Ubuntu 20.04+, Debian 10+, Alpine 3.19+ |
| RAM | 4 GB minimum (see the memory warning below) |
| Network | Always-on internet connection (responses stream from Anthropic servers) |
| Shell | Bash, Zsh, PowerShell, or CMD |
Windows users: You must have Git for Windows installed. Claude Code will not work without it on native Windows.
Node.js is NOT required. The native installer bundles everything. You may see older guides recommending npm install -g @anthropic-ai/claude-code -- that method is deprecated. Do not use it.
Choose Your Plan
You need a paid account. The free tier does not include Claude Code access.
| Plan | Price | Claude Code? | Who It's For |
|---|---|---|---|
| Free | $0 | No | Web chat only |
| Pro | $20/mo | Yes | Individual developers (start here) |
| Max | $100/mo | Yes | Power users who hit rate limits |
| Teams | $30/user/mo | Yes | Small-medium teams, centralized billing |
| Enterprise | Custom | Yes | SSO, compliance, admin controls |
| Console (API) | Pay-per-use | Yes | CI/CD, automation, pay only for what you use |
My recommendation: Start with Pro at $20/month. It includes Claude Code, Claude on the web, and the desktop app. If you hit rate limits, upgrade to Max.
What the Docs Don't Tell You About Costs
This is the single biggest source of frustration in the community, so let me be upfront.
Rate limits are real and aggressive. Pro users get a usage quota that resets on a rolling window. When you hit it, Claude Code stops working until the window resets. There is no clear documentation on exact limits -- Anthropic adjusts them dynamically. Expect roughly $6/day average on Sonnet, more on Opus.
Opus 4.6 consumes significantly more tokens than previous versions. Users have reported 20-30% higher consumption for identical tasks compared to Opus 4.5. The model is more verbose by design -- it generates nearly 3x more tokens than average models on benchmarks. If you are on a Pro or Max plan and burning through limits, switch to Sonnet for daily work and reserve Opus for complex problems.
Console (API) pricing is transparent but adds up. You pay per token at standard Claude API rates. A typical day of active development runs $6-12. Use --max-budget-usd in headless mode to cap spending.
Track your usage constantly. Type /cost during any session to see token consumption and estimated spend. This is not optional -- it is survival.
How to Sign Up
- Go to claude.ai and click Sign Up
- Create your account with email, Google, or Apple SSO
- Navigate to the pricing page and select your plan
- Enter payment details and confirm
- Your account is ready -- proceed to installation
Install Claude Code on macOS
macOS is the best-supported platform. Three options, ranked:
Option A: Native Installer (Recommended)
curl -fsSL https://claude.ai/install.sh | bash
Why this is the right choice: Auto-updates silently. No dependencies. No Node.js. You are always on the latest version with zero maintenance.
Verify it worked:
claude --version
If you see "command not found," close your terminal completely and open a new one. The PATH update requires a fresh shell.
Want the stable channel? New features are delayed ~1 week but more thoroughly tested:
curl -fsSL https://claude.ai/install.sh | bash -s stable
Need a specific version?
curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58
Option B: Homebrew
brew install --cask claude-code
The catch: No auto-updates. You must run brew upgrade claude-code manually. I have seen engineers run months-old versions without realizing it.
macOS Gotchas
- Gatekeeper warning on first run: macOS will show a security dialog. Click "Allow" or go to System Settings > Privacy & Security and approve it.
- Fish shell quirks: Claude Code works best with Zsh (default) or Bash. Fish works but some interactive features behave differently.
- PATH issues after Homebrew install: If
claudeis not found, runbrew link claude-codeor manually add the Homebrew bin to your PATH. - Apple Silicon vs Intel: Auto-detected. No action needed.
Install Claude Code on Windows
Windows support works, but it has rough edges. There are over 2,600 open Windows-specific issues on GitHub as of early 2026. My honest advice: use WSL if you can. If you cannot, the native installer works for most tasks.
Option A: WSL (Strongly Recommended)
This gives you a full Linux environment where Claude Code works exactly like it does on macOS:
# Run in PowerShell as Admin
wsl --install -d Ubuntu
Restart your computer. Open Ubuntu from the Start menu, then:
curl -fsSL https://claude.ai/install.sh | bash
claude --version
Why WSL is worth the setup:
- Bash tool sandboxing works properly (it does not on native Windows)
- File operations are significantly faster inside WSL (
/home/user/projects, not/mnt/c/Users/...) - All tutorials and documentation work without translation
- You avoid the Windows-specific bugs entirely
Important: You need WSL 2, not WSL 1. Check with wsl -l -v. WSL 1 does not support the sandboxing features Claude Code requires.
Option B: PowerShell Native Installer
Open PowerShell as Administrator:
irm https://claude.ai/install.ps1 | iex
Verify:
claude --version
Option C: WinGet
winget install Anthropic.ClaudeCode
No auto-updates. Run winget upgrade Anthropic.ClaudeCode periodically.
Option D: Git Bash
If you have Git for Windows installed:
curl -fsSL https://claude.ai/install.sh | bash
Windows Gotchas (The Real Ones)
These come from actual GitHub issues, not hypotheticals:
- Antivirus blocks the installer. Windows Defender or corporate antivirus may quarantine
claude.exe. Add an exception for%USERPROFILE%\.local\bin\claude.exe. - PowerShell execution policy blocks irm | iex. Fix:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser - Path length limit causes crashes. Windows defaults to 260-character paths. Deep
node_modulestrees break things. Fix:reg add HKLM\SYSTEM\CurrentControlSet\Control\FileSystem /v LongPathsEnabled /t REG_DWORD /d 1 /f - A literal file named "nul" gets created. This is a known bug --
nulis a reserved filename on Windows and Claude Code creates it by accident. Delete it manually. - Bash tool stdout silently lost. On native Windows, shell script output can be silently dropped. You will see Claude say "I ran the command" but show no output. This does not happen in WSL.
- Extremely slow file reads. The
cygpathtranslation layer on native Windows adds significant overhead to every file operation. - Shift+Tab does not work in PowerShell. The permission mode cycling shortcut is broken in native PowerShell.
- Line endings. Set
git config --global core.autocrlf inputto avoid CRLF issues. - Git for Windows is mandatory. The native Windows installer will not work without it.
Authenticate
Authentication happens once. Your credentials are stored securely after the first login.
cd ~/your-project
claude
Your browser opens automatically. Log in with your Claude account, authorize access, and you are returned to the terminal:
Welcome to Claude Code!
Session: new session
Model: claude-sonnet-4-20250514
Type /help for available commands
>
Manage Authentication
claude auth status # Check who you are logged in as
claude auth login # Log in or switch accounts
claude auth logout # Sign out
Inside an active session, type /login to switch accounts.
Authentication Gotcha
If you have an ANTHROPIC_API_KEY environment variable set (maybe from a previous API project), it overrides your Pro/Max subscription. You will see "Organization has been disabled" errors even though you are paying. Fix: unset ANTHROPIC_API_KEY or remove it from your shell profile.
Authentication Options
- Claude Pro/Max/Teams/Enterprise: Log in with your claude.ai account. Simplest option.
- Console (API): For pay-per-use access. A dedicated "Claude Code" workspace is automatically created for cost tracking.
- Cloud providers: Amazon Bedrock, Google Vertex AI, or Microsoft Foundry for enterprises with existing contracts.
Your First Real Session
Skip "hello world." Here is how to get real value immediately.
Understand a New Codebase
cd ~/projects/my-app
claude
Then type:
give me a high-level architecture overview of this project.
what are the main components, how do they connect, and where are the entry points?
Claude reads your file tree, examines key files, and gives you a structured summary. This alone is worth the subscription -- it turns hours of code reading into seconds.
Fix a Real Bug
the build is failing with "Module not found: Can't resolve './utils/helpers'"
-- find the broken import and fix it
Claude traces the import chain, finds the mismatch, and proposes the fix. You approve, it is done.
Write Tests
write comprehensive unit tests for src/lib/auth.ts
using the existing test patterns in this project
Claude examines your test directory, matches the style and framework you already use, and generates tests that actually pass.
Reference Files with @
You can reference specific files directly in your prompts:
explain @src/lib/auth.ts and how it connects to @src/middleware/session.ts
Claude loads those files into context automatically. You can also reference directories (@src/components) to get a listing.
Paste Screenshots
Copy an image and press Ctrl+V (or Cmd+V on Mac in iTerm2) to paste it directly into Claude Code. It can analyze UI screenshots, generate CSS from mockups, or debug visual bugs.
Multiline Input
Need to type a long prompt? Several options:
- Shift+Enter works out of the box in iTerm2, Kitty, Ghostty, and WezTerm
- Option+Enter on macOS
- Backslash + Enter (
\then Enter) works in any terminal - Ctrl+G opens your prompt in your
$EDITOR(Vim, VS Code, etc.) for complex multi-paragraph prompts
Set Up CLAUDE.md (The Secret Weapon)
This is the single most impactful thing you can do, and most people skip it. CLAUDE.md is a file that tells Claude about your project. It is read automatically at the start of every session.
Quick Start
claude
# Then inside the session:
/init
Claude analyzes your project, detects your tech stack, and generates a starter CLAUDE.md. Edit it to add your conventions.
Manual Setup
Create CLAUDE.md in your project root:
# Project Context
## Tech Stack
- Next.js 14 with App Router
- TypeScript strict mode
- Tailwind CSS, PostgreSQL with Prisma ORM
## Common Commands
- `npm run dev` - Start dev server
- `npm test` - Run tests
- `npm run lint` - Lint check
## Conventions
- Functional components with hooks, no class components
- Named exports, not default exports
- All API routes in src/app/api/
- Zod validation on all API inputs
- Conventional Commits (feat:, fix:, chore:)
## Important
- Never commit .env files
- Database migrations must be backward-compatible
The difference in output quality with vs. without this file is dramatic. It is like giving your AI pair programmer a one-page onboarding document.
The CLAUDE.md Hierarchy (Most People Don't Know This)
Claude Code supports five levels of configuration files, each with different scope:
| File | Who Sees It | In Git? | Use It For |
|---|---|---|---|
./CLAUDE.md | Everyone on the project | Yes | Team conventions, tech stack, commands |
./.claude/CLAUDE.md | Everyone on the project | Yes | Alternative location (same as above) |
~/.claude/CLAUDE.md | Just you, all projects | No | Personal preferences (preferred language, style) |
./.claude/CLAUDE.local.md | Just you, this project | No | Your overrides for this specific project |
./.claude/rules/*.md | Everyone on the project | Yes | Modular rules, organized by topic |
The modular rules directory is underutilized. Create .claude/rules/ with files like:
.claude/rules/
code-style.md
testing.md
security.md
api-conventions.md
You can even scope rules to specific file paths using YAML frontmatter:
---
paths:
- "src/api/**/*.ts"
---
# API Rules
- All endpoints must validate input with Zod
- Return consistent error shapes
- Log all 5xx errors
Memory: What Claude Remembers Between Sessions
Claude Code maintains its own memory about your project:
- Auto-memory: Claude saves notes about patterns, debugging insights, and your preferences at
~/.claude/projects/<project>/memory/ - 200 lines are loaded automatically at every session start
- View and edit: Type
/memoryto see what Claude remembers and correct anything wrong
Gotcha: Do not rely on conversation history for persistent instructions. When context compacts (more on this below), conversation details are summarized and can be lost. Put anything persistent in CLAUDE.md instead.
@ Imports in CLAUDE.md
You can reference other files:
For project overview, see @README.md
For npm commands, see @package.json
For git workflow, see @docs/git-instructions.md
Claude loads these files when it processes your CLAUDE.md.
Choose Your Model
You have three models. Picking the right one for each task is the single best way to manage costs and rate limits.
| Model | Speed | Quality | Cost | Use It For |
|---|---|---|---|---|
| Sonnet | Fast | Great for 90% of tasks | Lower | Daily development, code generation, debugging |
| Opus | Slow | Best reasoning, most thorough | Highest | Architecture decisions, complex multi-file refactoring |
| Haiku | Very fast | Good for simple tasks | Lowest | Quick questions, simple lookups, boilerplate |
How to Switch
During a session: Press Cmd+P (Mac) or Alt+P (Windows/Linux) to open the model picker.
From the command line:
claude --model sonnet
claude --model opus
claude --model haiku
In settings.json (persistent):
{
"model": "claude-sonnet-4-6"
}
Via environment variable:
export ANTHROPIC_MODEL=sonnet
Extended Thinking
Opus uses "extended thinking" by default -- it reasons through problems before responding. This produces significantly better results for complex tasks but uses more tokens. Toggle it with Cmd+T (Mac) or Alt+T (Windows).
Fast Mode
Same model, faster output, less deep reasoning. Toggle with /fast. Good for quick queries.
The Opus 4.6 Cost Trap
When Opus 4.6 launched, it was auto-enabled for many users without announcement. It uses 20-30% more tokens than Opus 4.5 for identical tasks because the model is more verbose. If your rate limits are suddenly being hit much faster than before, this is probably why.
Workaround: Pin to a specific Opus version in settings:
{
"model": "claude-opus-4-5",
"env": {
"ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-opus-4-5-20251101"
}
}
Or just use Sonnet for daily work. Honestly, Sonnet handles 90% of tasks just as well.
Understand Permission Modes
Claude Code has three modes that control how much autonomy it gets. Cycle between them with Shift+Tab.
| Mode | What Happens |
|---|---|
| Normal | Claude asks permission before every tool use (file edits, shell commands, etc.) |
| Auto-Accept | Allowed tools run automatically, unknown ones still prompt |
| Plan Mode | Read-only. Claude plans its approach, you approve before anything changes |
Start in Normal mode until you trust your setup. Switch to Auto-Accept once you have good allow/deny rules configured. Use Plan Mode when the change is complex and you want to review the approach first.
The "Always Allow" Bug
This is one of the most reported issues. When you select "Yes, always allow" for a file operation, Claude Code frequently continues to prompt for the same permission anyway. Workaround: define your permissions explicitly in .claude/settings.local.json instead of relying on the interactive prompts.
Set a default mode in your settings:
{
"permissions": {
"defaultMode": "plan"
}
}
Configure Settings
Settings are JSON files in a layered system. Higher-priority files override lower ones.
| File | Scope | In Git? | Priority |
|---|---|---|---|
~/.claude/settings.json | All your projects | No | Lowest |
.claude/settings.json | This project, everyone | Yes | Medium |
.claude/settings.local.json | This project, just you | No (gitignored) | Higher |
| Managed settings (IT-deployed) | Organization-wide | N/A | Highest |
Quick Configuration
Type /config inside Claude Code for an interactive settings menu.
Example settings.json
{
"model": "claude-sonnet-4-6",
"autoUpdatesChannel": "stable",
"permissions": {
"allow": [
"Bash(npm run *)",
"Bash(git *)",
"Read(./src/**)",
"Edit(./src/**)"
],
"deny": [
"Bash(curl *)",
"Bash(rm -rf *)",
"Bash(git push --force*)",
"Read(.env)",
"Read(.env.*)",
"Read(./secrets/**)"
]
}
}
Permission Pattern Gotchas
The pattern matching has subtle rules that trip people up:
- Space before
*matters.Bash(npm *)matchesnpm run build(word boundary).Bash(npm*)also matchesnpmx(no boundary). Always include the space. - Shell operators are checked.
Bash(safe-cmd *)will not matchsafe-cmd && dangerous-cmd. Claude is aware of&&,||, and pipes. - There is no .claudeignore file. Use
denyrules in settings instead..envandnode_modulesare NOT automatically excluded -- you must deny them explicitly. - Path prefixes:
./path= project relative,~/path= home directory,//path= absolute filesystem path (note the double slash).
Environment Variables
You can set environment variables in settings that affect Claude Code behavior:
{
"env": {
"ANTHROPIC_MODEL": "sonnet",
"DISABLE_AUTOUPDATER": "1",
"MAX_THINKING_TOKENS": "10000",
"CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "50"
}
}
The last one is useful: it makes context compaction trigger at 50% instead of 95%, preventing the sudden context loss that happens when you hit the wall.
Set Up MCP Servers
MCP (Model Context Protocol) is an open standard that connects Claude Code to external tools. This is where Claude Code goes from "smart terminal assistant" to "AI that can query your database, manage your GitHub, and search your Jira."
What MCP Servers Enable
- Query databases: "Find all customers who haven't purchased in 90 days"
- Manage GitHub: "Review PR #456 and suggest improvements"
- Monitor errors: "What are the top Sentry errors in production this week?"
- Search docs: "Find the architecture decision record for the auth migration in Confluence"
Adding MCP Servers
# Remote HTTP server (cloud services)
claude mcp add --transport http stripe https://mcp.stripe.com
# Local server (databases, local tools)
claude mcp add --transport stdio my-db -- npx -y @bytebase/dbhub
# Import all servers from Claude Desktop
claude mcp add-from-claude-desktop
# List and manage
claude mcp list
claude mcp remove stripe
MCP Scopes
| Scope | Stored In | Shared? | Use For |
|---|---|---|---|
local (default) | ~/.claude.json | No | Personal tools |
project | .mcp.json | Yes (git) | Team-shared tools |
user | ~/.claude.json | No | Cross-project personal tools |
MCP Gotchas (Important)
Every MCP server eats context permanently. Even idle servers add their tool definitions to every API request. A few servers can consume 5-10% of your context window before you type a single word. Only add servers you actively use.
MCP config can be deleted on auto-update. This is a known bug. Back up your .mcp.json before Claude Code updates. Or commit it to git (use project scope) so you can always recover.
No individual tool filtering. You cannot selectively enable specific tools from an MCP server -- it is all or nothing. If a server has 50 tools and you only need 3, all 50 still consume context.
OAuth authentication via /mcp. Run /mcp inside Claude Code to authenticate with servers that require OAuth. Tokens refresh automatically.
Set Up Hooks
Hooks run shell commands automatically at specific lifecycle points. They are deterministic -- they always execute, unlike asking Claude to "remember to format the code."
Practical Examples
Desktop notification when Claude needs your attention (add to settings.json):
{
"hooks": {
"Notification": [{
"matcher": "",
"hooks": [{
"type": "command",
"command": "osascript -e 'display notification \"Claude needs attention\" with title \"Claude Code\"'"
}]
}]
}
}
Linux equivalent: notify-send 'Claude Code' 'Needs your attention'
Auto-format after every file edit:
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command": "npx prettier --write $CLAUDE_FILE_PATH"
}]
}]
}
}
Hook Events
| Event | When It Fires |
|---|---|
SessionStart | Session begins or resumes |
UserPromptSubmit | You press Enter on a prompt |
PreToolUse | Before a tool runs (can block it) |
PostToolUse | After a tool succeeds |
PostToolUseFailure | After a tool fails |
Notification | Claude needs your attention |
Stop | Claude finishes a response |
PreCompact | Before context compaction |
SubagentStart | A subagent is spawned |
SubagentStop | A subagent finishes |
SessionEnd | Session terminates |
Create and manage hooks interactively with /hooks.
Master Session Management
Sessions are one of Claude Code's most powerful features, but most people only know claude -c.
Continue and Resume
claude -c # Continue the most recent session
claude -r "auth-refactor" # Resume a specific named session
claude -r "auth-refactor" "finish the PR" # Resume and immediately send a prompt
Inside a session:
/resume-- interactive session picker with search, preview, and rename/rename my-session-- give the current session a memorable name
The /resume Picker
The interactive picker has keyboard shortcuts most people don't know:
| Key | Action |
|---|---|
| / | Search sessions |
| P | Preview a session's content |
| R | Rename a session |
| A | Toggle between current directory and all projects |
| B | Filter by git branch |
Context Compaction (Critical to Understand)
As your session gets long, Claude's context window fills up. At ~95% capacity, auto-compaction kicks in. Claude summarizes older parts of the conversation to free space.
What you need to know:
- Old tool outputs (command results, file contents) are pruned first
- Then conversation history is summarized
- Detailed instructions from early in the session can be lost. This is why CLAUDE.md exists -- it is re-read fresh on every turn and never compacted.
- Compaction can occasionally corrupt a session, making it permanently broken. If this happens, start a new session.
Manual compaction: Type /compact to trigger it yourself. You can guide what gets preserved:
/compact focus on the API changes and test results
Trigger compaction earlier to avoid the sudden wall at 95%:
{
"env": {
"CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "50"
}
}
Git Worktrees
For isolated experiments, Claude Code supports git worktrees:
claude --worktree feature-auth
This creates a new branch at .claude/worktrees/feature-auth where Claude can work without affecting your main working directory. If no changes are made, the worktree is automatically cleaned up. If changes exist, you are prompted to keep or remove it.
Add .claude/worktrees/ to your .gitignore.
Use Subagents for Complex Work
Subagents are specialized AI assistants that run in their own context window. They keep your main conversation clean while handling focused tasks.
Built-in Subagents
| Agent | Model | Purpose |
|---|---|---|
| Explore | Haiku (fast) | Search codebase, find files, answer questions |
| Plan | Inherited | Research and design before implementation |
| General-purpose | Inherited | Complex multi-step tasks |
Claude uses these automatically when appropriate. You can also create your own.
Creating Custom Subagents
Run /agents or create a file at .claude/agents/code-reviewer.md:
---
name: code-reviewer
description: Reviews code for quality, security, and best practices
tools: Read, Grep, Glob
model: sonnet
maxTurns: 10
---
You are a senior code reviewer. Check for:
- Security vulnerabilities (OWASP Top 10)
- Performance anti-patterns
- Missing error handling
- Inconsistent naming conventions
Subagent Gotchas
- Subagents cannot spawn other subagents. No nesting. Chain them from the main conversation instead.
- Each subagent gets its own context window. They do not share context with each other or with your main session.
- Verbose subagent output stays in their context, not yours. This is actually a feature -- it keeps your main session clean.
Headless Mode for CI/CD
Claude Code runs non-interactively in pipelines. This is how I use it for automated code reviews, test generation, and deployment checks.
Basic Usage
# Run a query and exit
claude -p "summarize the changes in this PR"
# Output formats
claude -p "query" --output-format text # Plain text (default)
claude -p "query" --output-format json # Full JSON message log
claude -p "query" --output-format stream-json # Real-time streaming
# Cost and iteration limits
claude -p "refactor auth" --max-budget-usd 5.00
claude -p "fix tests" --max-turns 10
Pipe Anything Into Claude
npm test 2>&1 | claude -p "analyze these test failures and fix them"
cat error.log | claude -p "what caused this crash?"
git diff main | claude -p "review these changes for security issues"
Structured JSON Output
claude -p "list all API endpoints" --json-schema '{
"type": "array",
"items": {
"type": "object",
"properties": {
"method": {"type": "string"},
"path": {"type": "string"},
"description": {"type": "string"}
}
}
}'
Skip Permissions in Pipelines
claude -p "run tests and fix failures" --dangerously-skip-permissions
Only use this in sandboxed CI/CD environments. It lets Claude execute any command without confirmation.
GitHub Actions
- uses: anthropic-ai/claude-code-action@latest
with:
prompt: "Review this PR and suggest improvements"
max-turns: 20
GitLab CI/CD
claude-code:
image: docker.io/anthropics/claude-code:latest
script:
- claude -p "Review changes and run tests"
Integrate with Your Editor
VS Code
- Extensions (Cmd+Shift+X / Ctrl+Shift+X) > Search "Claude Code" > Install
- Open Claude Code from the sidebar
Features: prompt box with @file references, session resumption, commit and PR creation, plugin management.
JetBrains (IntelliJ, PyCharm, WebStorm)
- Settings > Plugins > Search "Claude Code" > Install > Restart
Works with all JetBrains IDEs. Supports WSL2 and remote development.
Claude Desktop App
Download from claude.ai for macOS or Windows. Graphical interface alongside the regular Claude chat experience.
Cursor
Claude Code works as a standalone terminal tool. Run claude in Cursor's integrated terminal for the best of both worlds.
Every Command You Need
Terminal Commands
| Command | What It Does |
|---|---|
claude | Start interactive session |
claude "fix the tests" | Start with initial prompt |
claude -p "explain this" | Query, print response, exit |
claude -c | Continue most recent session |
claude -r "name" | Resume a named session |
claude --model opus | Start with specific model |
claude --worktree feature-x | Start in isolated git worktree |
claude --add-dir ../lib | Add extra directories to context |
claude update | Update to latest version |
claude doctor | Diagnose environment issues |
claude auth status | Check authentication |
claude auth login | Sign in or switch accounts |
claude mcp list | List MCP servers |
claude mcp add | Add an MCP server |
claude --version | Show version |
Session Slash Commands
| Command | What It Does |
|---|---|
/help | Show all available commands |
/init | Generate a CLAUDE.md for your project |
/config | Settings menu (model, theme, updates) |
/model | Change model |
/fast | Toggle fast mode |
/memory | View and edit what Claude remembers |
/cost | Token usage and cost for this session |
/status | Show active configuration and context usage |
/compact | Manually trigger context compaction |
/resume | Interactive session picker |
/rename | Rename current session |
/rewind | Rewind to a checkpoint or undo recent changes |
/clear | Clear conversation history |
/mcp | Manage MCP servers and OAuth |
/hooks | Configure lifecycle hooks |
/agents | List or create subagents |
/vim | Toggle Vim keybindings |
/keybindings | Customize keyboard shortcuts |
/login | Switch accounts |
/bug | Report a bug |
/feedback | Send feature feedback |
Keyboard Shortcuts
| Shortcut | Action |
|---|---|
| Ctrl+C | Cancel current operation |
| Ctrl+D | Exit Claude Code |
| Enter | Submit message |
| Escape | Cancel input |
| Shift+Tab | Cycle permission modes |
| Cmd/Alt+P | Model picker |
| Cmd/Alt+T | Toggle extended thinking |
| Ctrl+R | Search command history |
| Ctrl+O | Toggle verbose transcript (see Claude's thinking) |
| Ctrl+G | Open prompt in external editor ($EDITOR) |
| Ctrl+S | Stash current prompt |
| Ctrl+V | Paste image |
| Ctrl+T | Toggle task list |
| Ctrl+F | Kill all background agents (press twice to confirm) |
| Ctrl+L | Clear terminal (keeps history) |
| Tab | Accept autocomplete |
Multiline input: Shift+Enter (iTerm2/Kitty/Ghostty/WezTerm), Option+Enter (macOS), \+Enter (any terminal), or Ctrl+J.
Customize everything with /keybindings. Changes take effect immediately.
Real-World Gotchas
These come from tracking thousands of GitHub issues and personal experience. You will not find most of these in the official documentation.
Memory Leaks in Long Sessions
During extended sessions (30-60+ minutes), the Claude Code process can grow to consume all available system RAM. Users on 128GB machines have reported the process reaching 120GB+ before being killed by the OS. After restart, memory starts at ~400MB and grows again.
Workaround: Restart Claude Code periodically during long sessions. There is no automated fix. Use claude -c to continue where you left off.
The .claude.json Bloat Problem
Every conversation across all projects is stored indefinitely in ~/.claude.json with no rotation. Users report this file growing to 90MB+, causing noticeably slower startup times. MCP server configuration lives in the same file, so you cannot just delete it.
Workaround: Periodically edit ~/.claude.json manually and prune old history entries. Be careful not to delete MCP config sections.
Context Compaction Can Break Sessions
Auto-compaction at 95% context usage can occasionally get stuck at 0% or corrupt the conversation state entirely. When this happens, the session becomes permanently unusable.
Workaround: Start a new session with claude. Use /compact proactively before hitting the wall. Set CLAUDE_AUTOCOMPACT_PCT_OVERRIDE to trigger earlier.
API Overload Errors (529)
During peak usage, you may see "529 API Overloaded" errors. Claude Code has built-in retry logic (up to 10 retries with exponential backoff), but sometimes the API stays overloaded for extended periods.
Workaround: Switch to a less-demanded model (Haiku instead of Opus). Wait and retry. There is nothing else you can do.
Stale git index.lock Files
Claude Code occasionally leaves behind .git/index.lock files, which block all your own git commands until deleted.
Fix: rm .git/index.lock
Session Permissions Do Not Persist on Resume
When you resume a session with claude -c or /resume, permissions you previously approved do not carry over. You will get prompted again for the same operations.
MCP Tools Flood Context
All MCP tools are loaded eagerly. If you have many servers configured, their combined tool definitions can consume 5-10% of your context window before you start working.
Workaround: Only configure servers you actively use. Remove idle ones with claude mcp remove.
Temp File Leaks
Claude Code creates /tmp/claude-*-cwd files for working directory tracking and never cleans them up. They accumulate over time.
Cleanup: rm /tmp/claude-*-cwd
Troubleshooting
"command not found: claude"
Close and reopen your terminal. If that does not work:
# macOS/Linux -- check where it installed
ls ~/.local/bin/claude
# Add to PATH manually
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
On Windows:
Test-Path "$env:USERPROFILE\.local\bin\claude.exe"
# If True but not found, restart your terminal
Authentication Fails
- Verify you have an active paid subscription. Free accounts do not include Claude Code.
- If the browser redirect fails, log in at claude.ai first, then retry
claude. - Unset
ANTHROPIC_API_KEYif you have one (it overrides your subscription). - Corporate firewalls may block OAuth. Ask IT to allow
claude.aiandanthropic.comdomains. - Check status:
claude auth status
Slow Responses
- Check your internet connection -- everything streams from Anthropic's servers
- Disconnect VPN temporarily
- Switch to Haiku for quick queries
- Large files (10,000+ lines) are slow. Point Claude to specific functions instead.
Concurrency Errors (HTTP 400)
If you see tool use concurrency errors, the conversation state is broken.
Fix: Type /rewind to roll back to the last good state.
Permission Errors on macOS
chmod +x ~/.local/bin/claude
Windows Defender Blocking
Add exclusion: Windows Security > Virus & Threat Protection > Manage Settings > Exclusions > add %USERPROFILE%\.local\bin\
claude doctor Hangs
claude doctor can get stuck at 100% CPU. Kill it with Ctrl+C and try again after restarting your terminal.
Nuclear Reset
When all else fails:
# Remove everything
rm -f ~/.local/bin/claude
rm -rf ~/.local/share/claude
rm -rf ~/.claude
rm -f ~/.claude.json
# Reinstall
curl -fsSL https://claude.ai/install.sh | bash
claude --version
On Windows PowerShell:
Remove-Item -Path "$env:USERPROFILE\.local\bin\claude.exe" -Force
Remove-Item -Path "$env:USERPROFILE\.local\share\claude" -Recurse -Force
Remove-Item -Path "$env:USERPROFILE\.claude" -Recurse -Force
Remove-Item -Path "$env:USERPROFILE\.claude.json" -Force
irm https://claude.ai/install.ps1 | iex
Uninstalling Claude Code
macOS/Linux:
rm -f ~/.local/bin/claude
rm -rf ~/.local/share/claude
Windows PowerShell:
Remove-Item -Path "$env:USERPROFILE\.local\bin\claude.exe" -Force
Remove-Item -Path "$env:USERPROFILE\.local\share\claude" -Recurse -Force
Homebrew: brew uninstall --cask claude-code
WinGet: winget uninstall Anthropic.ClaudeCode
Remove all settings, memory, and history: Delete ~/.claude and ~/.claude.json.
Wrapping Up
Claude Code is the most powerful AI coding tool available today, and also the most complex to set up properly. The official docs give you the commands. This guide gives you everything else -- the cost traps, the Windows bugs, the memory leaks, the permission quirks, the features that transform Claude Code from a novelty into a daily workhorse.
The key things most people miss:
- Set up CLAUDE.md -- it is the single highest-ROI thing you can do
- Use Sonnet for daily work -- save Opus for hard problems
- Track costs with /cost -- rate limits are aggressive
- Restart periodically -- memory leaks are real
- Use WSL on Windows -- native Windows has too many bugs
- Configure deny rules -- Claude will read your .env if you let it
- Back up .mcp.json -- auto-updates can delete it
If you found this useful, check out my other posts on AI-powered cloud engineering and building self-healing infrastructure with Claude Code.
Have questions or a gotcha I missed? Reach out on LinkedIn or GitHub.