Claude Code CLI

Claude Code is Anthropic’s agentic coding tool — a claude binary that reads your codebase, edits files, runs commands, and integrates with IDEs, the web app, the desktop app, and CI. Under the hood it’s the Claude Agent SDK with a curated tool set (Read, Write, Edit, Bash, Grep, Glob, Task, etc.), permission modes, hooks, skills, and a settings.json hierarchy. This note covers everything: installation, every CLI flag, the settings.json schema, environment variables, permission modes, the statusline, and authentication. The hooks system gets its own deep note (claude-code-hooks-deep); subagents and skills also get a dedicated note (claude-code-subagents-and-skills).

See also

1. What Claude Code is

Per code.claude.com/docs/en/overview:

  • An agentic coding tool that reads your codebase, edits files, runs commands, and integrates with your dev environment.
  • Available as Terminal CLI, VS Code extension, Cursor extension, JetBrains plugin, Desktop app (macOS / Windows / Windows ARM64), Web (claude.ai/code), and on iOS via the Claude app.
  • All surfaces share one engine + one configuration: CLAUDE.md, settings, MCP servers, skills work everywhere.

Authentication options:

  • Claude Pro / Max subscription (claude auth login) — preferred for individuals; subscription quota covers usage
  • Anthropic Console / API key (claude auth login --console) — pay-as-you-go via API key
  • Amazon Bedrock (CLAUDE_CODE_USE_BEDROCK=1 + AWS creds)
  • Claude Platform on AWS (CLAUDE_CODE_USE_ANTHROPIC_AWS=1 + ANTHROPIC_AWS_WORKSPACE_ID)
  • Google Vertex AI (CLAUDE_CODE_USE_VERTEX=1 + GCP creds)
  • Microsoft Foundry (CLAUDE_CODE_USE_FOUNDRY=1 + Azure creds)

2. Installation

macOS, Linux, WSL:

curl -fsSL https://claude.ai/install.sh | bash

Windows PowerShell:

irm https://claude.ai/install.ps1 | iex

Windows CMD:

curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

On native Windows, Git for Windows is recommended so Claude Code can use the Bash tool; without it, Claude Code falls back to PowerShell.

Other installers

  • Homebrew (macOS): brew install --cask claude-code (stable channel) or brew install --cask claude-code@latest (latest)
  • WinGet: winget install Anthropic.ClaudeCode
  • apt / dnf / apk on Debian / Fedora / RHEL / Alpine — per Install with Linux package managers
  • claude install [version] — install/reinstall the native binary at a specific version (e.g. claude install stable, claude install 2.1.118)

Native installations auto-update in the background. Homebrew and WinGet need manual upgrade.

3. CLI commands (subcommands)

Per code.claude.com/docs/en/cli-reference. Top-level commands:

CommandPurpose
claudeStart interactive session in current dir
claude "query"Start interactive session with initial prompt
claude -p "query"Print mode (SDK-style), execute query then exit
cat file | claude -p "query"Process piped stdin
claude -c / claude --continueContinue most recent conversation in current dir
claude -r "<session>" "query" / --resumeResume session by ID or name
claude updateUpdate to latest
claude install [version]Install/reinstall binary
claude auth loginSign in (Claude subscription by default; --console for API key, --sso, --email)
claude auth logoutSign out
claude auth statusShow auth status as JSON (--text for human form). Exit 0 logged in, 1 if not.
claude agentsOpen agent view to monitor + 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 respawn <id>Restart background session, conversation intact
claude rm <id>Remove background session from list (transcript persists for --resume)
claude stop <id> / claude kill <id>Stop background session
claude mcp ...Manage MCP servers (see mcp-protocol)
claude plugin ... / claude plugins ...Manage plugins
claude project purge [path]Delete all local Claude Code state for a project
claude setup-tokenGenerate long-lived OAuth token for CI/scripts (Claude subscription)
claude remote-controlStart remote-control server for claude.ai / mobile app integration
claude --remote "task"Create new claude.ai web session
claude --teleportResume a web session in your local terminal
claude auto-mode defaultsPrint built-in auto-mode classifier rules as JSON
claude daemon statusBackground-session supervisor diagnostics
claude ultrareview [target]Run non-interactive ultrareview

Typo-correcting: claude udpateDid you mean claude update? and exits.

4. CLI flags (selected)

Per the cli-reference. Not every flag appears in claude --help — the docs are authoritative.

Session control

FlagWhat it does
--print, -pPrint mode (one-shot, exits)
--continue, -cLoad most recent conversation in cwd
--resume <id|name>, -rResume specific session
--session-id <uuid>Use specific UUID for the session
--fork-sessionWhen resuming, fork to new session ID
--name <name>, -nDisplay name for session
--from-pr <ref>Resume sessions linked to a PR (number, GitHub/GitLab/Bitbucket URL)
--bg "task"Start as background agent, return immediately
--worktree <name>, -wStart in isolated git worktree
--tmux / --tmux=classicCreate tmux session for worktree

Model + thinking

FlagWhat it does
--model <alias|id>Override model (sonnet, opus, haiku, or full ID like claude-opus-4-7)
--fallback-model <id>Fallback when default is overloaded (print mode + bg only)
--effort <low|medium|high|xhigh|max>Set effort level for this session
--betas <list>Beta headers to include (API key users only)
--max-turns <N>Cap agentic turns (print mode)
--max-budget-usd <amt>Cap dollar spend (print mode)

Tools + permissions

FlagWhat it does
--allowedTools <patterns>Pre-approve tools (no permission prompt). Pattern syntax: Bash(git *), Read, Edit(*.py)
--disallowedTools <patterns>Deny rules. Bare name removes from model context; scoped (Bash(rm *)) denies matching calls only
--tools <list>Restrict which built-in tools Claude can use. "" = all off; "default" = all; "Bash,Edit,Read" = whitelist
--add-dir <path>...Additional working directories (file access; most config not discovered)
--permission-mode <mode>default, acceptEdits, plan, auto, dontAsk, bypassPermissions
--dangerously-skip-permissionsSkip all permission prompts (equivalent to --permission-mode bypassPermissions)
--allow-dangerously-skip-permissionsAdd bypassPermissions to Shift+Tab cycle without starting in it
--permission-prompt-tool <mcp_tool>MCP tool to handle permission prompts in non-interactive mode

System prompt

FlagWhat it does
--system-prompt "text"Replace default system prompt
--system-prompt-file <path>Replace with file contents
--append-system-prompt "text"Append to default prompt
--append-system-prompt-file <path>Append file contents
--exclude-dynamic-system-prompt-sectionsMove per-machine sections (cwd, env, memory paths, git flag) to first user message. Improves cache hit across users/machines for the same task. Only with default system prompt.

Agents + plugins

FlagWhat it does
--agent <name>Run as specific subagent for this session
--agents '<json>'Define subagents dynamically via JSON
--teammate-mode <auto|in-process|tmux>Display mode for agent teammates
--plugin-dir <path>Load plugin from directory or .zip for this session only (repeatable)
--plugin-url <url>Fetch plugin .zip from URL (repeatable)

MCP

FlagWhat it does
--mcp-config <files>Load MCP servers from JSON files/strings (space-separated)
--strict-mcp-configOnly use servers from --mcp-config, ignore others
--channels <list>(Research preview) Listen for channel notifications from MCP servers

Output + I/O

FlagWhat it does
--output-format <text|json|stream-json>Print-mode output format
--input-format <text|stream-json>Print-mode input format
--include-hook-eventsInclude hook events in stream-json output
--include-partial-messagesInclude partial streaming events
--replay-user-messagesRe-emit user msgs from stdin on stdout for ack
--json-schema '<json>'Validate output against schema (print mode)

Diagnostics + misc

FlagWhat it does
--debug "categories"Enable debug. Examples: api,hooks, !statsig,!file (exclude)
--debug-file <path>Write debug logs to specific file
--verboseFull turn-by-turn output
--version, -vPrint version
--bareMinimal mode — skip auto-discovery of hooks/skills/plugins/MCP/auto-memory/CLAUDE.md. Faster scripted calls. Tools: Bash, Read, Edit only. Sets CLAUDE_CODE_SIMPLE=1.
--initRun Setup hooks with init matcher before session (print mode)
--init-onlyRun Setup + SessionStart hooks, then exit
--maintenanceRun Setup hooks with maintenance matcher (print mode)
--no-session-persistenceDon’t save session to disk (print mode)
--disable-slash-commandsDisable all skills and commands for this session
--chrome / --no-chromeToggle Chrome browser integration
--ideAuto-connect to IDE if exactly one valid IDE is available
--settings <path|json>Override settings.json for this session (path or inline JSON)
--setting-sources <list>Comma-separated user,project,local sources to load

5. Permission modes

Per code.claude.com/docs/en/permission-modes:

ModeBehavior
defaultStandard permission prompts
acceptEditsAuto-accept file edits + common filesystem commands in cwd / additionalDirectories
planPlan mode — Claude analyzes and produces a plan, no writes
autoAuto mode — background classifier reviews commands + protected-directory writes
dontAskAuto-deny permission prompts (explicitly allowed tools still work)
bypassPermissionsSkip all prompts. Equivalent to --dangerously-skip-permissions.

Cycle modes interactively with Shift+Tab. Set default via permissions.defaultMode in settings or --permission-mode on launch.

6. settings.json

Three locations, lowest-to-highest precedence:

ScopeLocationShared?
User~/.claude/settings.json (Windows: %USERPROFILE%\.claude\settings.json)No
Project.claude/settings.json in project rootYes (check into git)
Local.claude/settings.local.jsonNo (gitignored)
Managed/Library/Application Support/ClaudeCode/ (macOS), /etc/claude-code/ (Linux/WSL), C:\Program Files\ClaudeCode\ (Windows)Yes (admin-deployed)

Precedence (highest wins): managed > CLI args > local > project > user.

Selected keys

Core

  • model — default model (e.g. "claude-sonnet-4-6")
  • modelOverrides — map Anthropic IDs → provider-specific IDs
  • availableModels — whitelist models in /model picker
  • outputStyle — output style preset
  • language — preferred response language
  • agent — run as named subagent at session start

Permissions

  • permissions.allow[] — allowed tool patterns
  • permissions.ask[] — confirmation-required patterns
  • permissions.deny[] — blocked patterns
  • permissions.additionalDirectories[] — extra working directories
  • permissions.defaultMode — default mode
  • allowedHttpHookUrls[] — allowlist for HTTP hooks
  • httpHookAllowedEnvVars[] — env vars HTTP hooks can interpolate
  • disableBypassPermissionsMode — block bypass mode
  • skipDangerousModePermissionPrompt — skip bypass confirmation

Managed-only (admin)

  • allowedMcpServers[] / deniedMcpServers[]
  • allowManagedHooksOnly / allowManagedMcpServersOnly / allowManagedPermissionRulesOnly
  • claudeMd — org-managed CLAUDE.md
  • forceLoginMethod (claudeai or console)
  • forceLoginOrgUUID

Files + memory

  • autoMemoryEnabled (default true)
  • autoMemoryDirectory
  • claudeMdExcludes[] — glob patterns to exclude
  • plansDirectory

UI

  • editorMode (normal or vim)
  • tui (fullscreen or default)
  • viewMode (default, verbose, focus)
  • autoScrollEnabled, spinnerTipsEnabled, spinnerVerbs
  • showTurnDuration, showThinkingSummaries
  • prefersReducedMotion
  • preferredNotifChannel (auto, terminal_bell, iterm2, kitty, ghostty)
  • syntaxHighlightingDisabled

Hooks + customization

  • hooks — see claude-code-hooks-deep
  • disableAllHooks
  • statusLine — custom status line (per code.claude.com/docs/en/statusline)
  • fileSuggestion — custom @ file autocomplete script
  • autoMode — auto-mode classifier rules

Env + creds

  • env — env vars set for all sessions
  • apiKeyHelper — script that returns API key
  • awsCredentialExport / awsAuthRefresh / gcpAuthRefresh
  • otelHeadersHelper — dynamic OTel headers

Git + dev

  • attribution — commit/PR attribution customization
  • includeCoAuthoredBy (deprecated; use attribution)
  • includeGitInstructions (default true)
  • prUrlTemplate
  • respectGitignore (default true)

Updates

  • autoUpdatesChannel (stable or latest)
  • minimumVersion

Worktree

  • worktree.baseRef (fresh or head)
  • worktree.symlinkDirectories[]
  • worktree.sparsePaths[]
  • worktree.bgIsolation (worktree or none)

Sandbox (per code.claude.com/docs/en/sandbox)

  • sandbox.enabled (default false)
  • sandbox.failIfUnavailable
  • sandbox.autoAllowBashIfSandboxed
  • sandbox.excludedCommands[]
  • sandbox.allowUnsandboxedCommands
  • sandbox.filesystem.{allowWrite,denyWrite,denyRead,allowRead}[]
  • sandbox.network.{allowedDomains,deniedDomains,allowUnixSockets,allowAllUnixSockets,allowLocalBinding,allowMachLookup,httpProxyPort,socksProxyPort}
  • sandbox.enableWeakerNestedSandbox / sandbox.enableWeakerNetworkIsolation

Skills + MCP

  • maxSkillDescriptionChars (default 1536)
  • skillListingBudgetFraction (default 0.01 = 1% of context)
  • skillOverrides — per-skill visibility (on, name-only, user-invocable-only, off)
  • enableAllProjectMcpServers
  • enabledMcpjsonServers[] / disabledMcpjsonServers[]

Other

  • companyAnnouncements
  • defaultShell (bash or powershell)
  • cleanupPeriodDays (default 30, min 1)
  • awaySummaryEnabled
  • feedbackSurveyRate
  • disableAgentView, disableAutoMode, disableDeepLinkRegistration, disableRemoteControl, disableSkillShellExecution
  • parentSettingsBehavior (first-wins or merge)

Permission rule syntax

Per code.claude.com/docs/en/settings#permission-rule-syntax:

  • ToolName — exact tool name (e.g. Edit, Write)
  • ToolName(pattern) — scoped, e.g. Bash(git *), Bash(rm -rf *), Read(*.env), Edit(src/**/*.ts)
  • mcp__SERVER__TOOL — MCP tools, e.g. mcp__github__create_pr
  • Agent(name) — restrict which subagents the agent tool can invoke
  • Skill(name) / Skill(name *) — restrict skills

Example settings.json

{
  "model": "claude-sonnet-4-6",
  "permissions": {
    "defaultMode": "default",
    "allow": ["Read", "Bash(git *)", "Bash(npm test)", "Edit(src/**)"],
    "ask": ["Bash(rm *)", "Edit(.env*)"],
    "deny": ["Bash(curl *evil*)", "WebFetch"]
  },
  "env": {
    "NODE_ENV": "development"
  },
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{"type": "command", "command": "npm run lint"}]
    }]
  },
  "statusLine": {
    "type": "command",
    "command": "node ~/.claude/statusline.js"
  }
}

7. Environment variables

Per code.claude.com/docs/en/env-vars:

API + model

  • ANTHROPIC_API_KEY — API key
  • ANTHROPIC_AUTH_TOKEN — alternate auth token (Bearer)
  • ANTHROPIC_BASE_URL — custom endpoint (proxies / Foundry-style routes)
  • ANTHROPIC_MODEL — default model
  • ANTHROPIC_SMALL_FAST_MODEL — model for fast operations (statusline, etc.)

Cloud providers

  • CLAUDE_CODE_USE_BEDROCK=1 + AWS_PROFILE / AWS_REGION etc.
  • CLAUDE_CODE_USE_VERTEX=1 + GOOGLE_APPLICATION_CREDENTIALS + GCLOUD_PROJECT
  • CLAUDE_CODE_USE_FOUNDRY=1 + Azure creds
  • CLAUDE_CODE_USE_ANTHROPIC_AWS=1 + ANTHROPIC_AWS_WORKSPACE_ID

Behavior

  • CLAUDE_CODE_ENABLE_TELEMETRY / CLAUDE_CODE_DISABLE_TELEMETRY
  • CLAUDE_CODE_DISABLE_THINKING — force thinking off
  • CLAUDE_CODE_DISABLE_AUTO_MEMORY
  • CLAUDE_CODE_DISABLE_AGENT_VIEW
  • CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY
  • CLAUDE_CODE_ENABLE_AWAY_SUMMARY
  • CLAUDE_CODE_NO_FLICKER — use fullscreen renderer
  • CLAUDE_CODE_EFFORT_LEVEL
  • CLAUDE_CODE_USE_POWERSHELL_TOOL — enable PowerShell tool on Windows
  • CLAUDE_CODE_AUTO_CONNECT_IDE
  • CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL
  • CLAUDE_CODE_API_KEY_HELPER_TTL_MS
  • CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS
  • CLAUDE_CODE_SKIP_PROMPT_HISTORY — disable transcript writes
  • CLAUDE_CODE_SIMPLE=1 — set by --bare
  • CLAUDE_CODE_MAX_OUTPUT_TOKENS — cap output tokens per request
  • CLAUDE_CODE_SUBAGENT_MODEL — override subagent model regardless of definition
  • CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 — load CLAUDE.md from --add-dir paths
  • DISABLE_AUTOUPDATER
  • CLAUDE_PROJECT_DIR — set in hook / MCP server processes; project root path

Bash + shell

  • BASH_DEFAULT_TIMEOUT_MS (default 120000)
  • BASH_MAX_TIMEOUT_MS (default 600000)
  • BASH_MAX_OUTPUT_LENGTH — bash output cap (default 30000)
  • MAX_THINKING_TOKENS — extended-thinking budget cap

MCP

  • MCP_TIMEOUT — server startup timeout (ms)
  • MCP_TOOL_TIMEOUT — per-tool-call timeout (ms)
  • MAX_MCP_OUTPUT_TOKENS (default 25000)
  • ENABLE_TOOL_SEARCH (true, false, auto, auto:N)
  • ENABLE_CLAUDEAI_MCP_SERVERS (default true)
  • SLASH_COMMAND_TOOL_CHAR_BUDGET — fixed char budget for skill descriptions

Remote / web

  • CLAUDE_CODE_REMOTE"true" in web environments
  • CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX — prefix for auto-generated remote-control session names

OpenTelemetry

  • OTEL_METRICS_EXPORTER (otlp, etc.)
  • OTEL_EXPORTER_OTLP_ENDPOINT
  • OTEL_EXPORTER_OTLP_HEADERS

UI / shell

  • NO_COLOR / FORCE_COLOR
  • TERM

8. Slash commands

Per code.claude.com/docs/en/commands. Built-in commands available in any session:

CommandPurpose
/helpShow help
/clearClear conversation context
/compactCompact (summarize older messages)
/costShow session cost
/initInitialize CLAUDE.md for project (bundled skill)
/login / /logoutAuth management
/memoryEdit CLAUDE.md / auto-memory
/modelChange model
/agent / /agentsSubagent management UI
/skillsSkills manager
/mcpMCP server management
/permissionsEdit permission rules
/hooksHooks management
/statuslineConfigure statusline
/add-dir <path>Add working directory
/resume / /renameSession management
/statusSession status
/reviewBundled skill: code review
/pr-commentsAddress PR comments
/exportExport conversation
/ideIDE management
/vimVim mode
/desktopHand off session to desktop app
/loop <interval> /skillRepeat a skill on interval (bundled)
/scheduleCreate routine (cron-style)
/teleportPull web session into terminal
/run, /verify, /run-skill-generatorBundled launch + verify skills
/debug, /batch, /code-review, /claude-api, /security-reviewOther bundled skills

Custom slash commands

A .md file at .claude/commands/<name>.md becomes the /<name> slash command. The file format is identical to a skill — frontmatter + markdown body. Custom commands were merged into Skills; a .claude/commands/deploy.md and a .claude/skills/deploy/SKILL.md both create /deploy with identical semantics.

Body supports:

  • $ARGUMENTS — full argument string
  • $0, $1, $2 — positional args (shell-style quoted)
  • $name — named args declared in arguments: frontmatter
  • !`bash command` — execute bash, replace with stdout before prompt sent to model
  • ${CLAUDE_SESSION_ID}, ${CLAUDE_EFFORT}, ${CLAUDE_SKILL_DIR}
  • ```! fenced code block for multi-line bash injection
  • @path/to/file — auto-attach file content

9. Statusline

Per code.claude.com/docs/en/statusline. Configure via statusLine in settings:

{
  "statusLine": {
    "type": "command",
    "command": "node ~/.claude/statusline.js"
  }
}

The command runs every ~5 seconds; stdout becomes the statusline. Receives JSON on stdin: {session_id, model, cwd, transcript_path, ...}. Output up to ~80 chars.

Example statusline:

#!/usr/bin/env node
const input = require('fs').readFileSync(0, 'utf-8');
const { model, cwd } = JSON.parse(input);
const branch = require('child_process').execSync('git branch --show-current 2>/dev/null', {cwd}).toString().trim();
console.log(`${model.split('-').slice(-2,-1)[0].toUpperCase()} | ${branch || cwd}`);

10. Authentication precedence

Per code.claude.com/docs/en/authentication:

  1. CLI flag (--model, etc.)
  2. Environment variable (ANTHROPIC_API_KEY etc.)
  3. apiKeyHelper script in settings
  4. claude.ai session (/login)

Run /status or claude auth status to see which is currently active. Note: claude.ai MCP connectors only load when the claude.ai subscription is the active auth — env vars or apiKeyHelper will hide them.

11. Sessions and persistence

Per code.claude.com/docs/en/sessions:

  • Sessions stored at ~/.claude.json (metadata) + ~/.claude/projects/<encoded-cwd>/<session-uuid>.jsonl (transcript)
  • claude --continue finds most recent session in cwd
  • claude --resume shows interactive picker (incl. background sessions as of v2.1.144)
  • claude --fork-session --resume <id> creates a new session ID branched from the old one
  • Per-project state: ~/.claude/projects/<encoded-cwd>/ — purge with claude project purge <path>

12. Background agents and dispatch

Per code.claude.com/docs/en/agent-view:

  • claude --bg "task" starts session as background agent, returns session ID
  • claude agents opens monitor UI
  • claude attach <id>, claude logs <id>, claude respawn <id>, claude stop <id>, claude rm <id>
  • A supervisor daemon (claude daemon) coordinates background sessions
  • Up to 12 background workers by default

13. Common debugging commands

  • claude --debug "api,mcp" — selective debug categories
  • claude --debug-file /tmp/claude.log — write debug to file
  • /doctor — diagnostic summary (skill budget overflow, missing tools, etc.)
  • claude --verbose — full turn-by-turn output

14. Further reading