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
- claude-code-hooks-deep — full hook event coverage
- claude-code-subagents-and-skills — subagents, skills, the Task/Agent tool
- claude-agent-sdk — the programmatic SDK (same engine)
- mcp-protocol — MCP server integration
- hidden-tricks-and-gotchas — undocumented flags and env vars
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
Native install (recommended — auto-updates)
macOS, Linux, WSL:
curl -fsSL https://claude.ai/install.sh | bashWindows PowerShell:
irm https://claude.ai/install.ps1 | iexWindows CMD:
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmdOn 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) orbrew 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:
| Command | Purpose |
|---|---|
claude | Start 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 --continue | Continue most recent conversation in current dir |
claude -r "<session>" "query" / --resume | Resume session by ID or name |
claude update | Update to latest |
claude install [version] | Install/reinstall binary |
claude auth login | Sign in (Claude subscription by default; --console for API key, --sso, --email) |
claude auth logout | Sign out |
claude auth status | Show auth status as JSON (--text for human form). Exit 0 logged in, 1 if not. |
claude agents | Open 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-token | Generate long-lived OAuth token for CI/scripts (Claude subscription) |
claude remote-control | Start remote-control server for claude.ai / mobile app integration |
claude --remote "task" | Create new claude.ai web session |
claude --teleport | Resume a web session in your local terminal |
claude auto-mode defaults | Print built-in auto-mode classifier rules as JSON |
claude daemon status | Background-session supervisor diagnostics |
claude ultrareview [target] | Run non-interactive ultrareview |
Typo-correcting: claude udpate → Did 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
| Flag | What it does |
|---|---|
--print, -p | Print mode (one-shot, exits) |
--continue, -c | Load most recent conversation in cwd |
--resume <id|name>, -r | Resume specific session |
--session-id <uuid> | Use specific UUID for the session |
--fork-session | When resuming, fork to new session ID |
--name <name>, -n | Display 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>, -w | Start in isolated git worktree |
--tmux / --tmux=classic | Create tmux session for worktree |
Model + thinking
| Flag | What 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
| Flag | What 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-permissions | Skip all permission prompts (equivalent to --permission-mode bypassPermissions) |
--allow-dangerously-skip-permissions | Add 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
| Flag | What 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-sections | Move 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
| Flag | What 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
| Flag | What it does |
|---|---|
--mcp-config <files> | Load MCP servers from JSON files/strings (space-separated) |
--strict-mcp-config | Only use servers from --mcp-config, ignore others |
--channels <list> | (Research preview) Listen for channel notifications from MCP servers |
Output + I/O
| Flag | What it does |
|---|---|
--output-format <text|json|stream-json> | Print-mode output format |
--input-format <text|stream-json> | Print-mode input format |
--include-hook-events | Include hook events in stream-json output |
--include-partial-messages | Include partial streaming events |
--replay-user-messages | Re-emit user msgs from stdin on stdout for ack |
--json-schema '<json>' | Validate output against schema (print mode) |
Diagnostics + misc
| Flag | What it does |
|---|---|
--debug "categories" | Enable debug. Examples: api,hooks, !statsig,!file (exclude) |
--debug-file <path> | Write debug logs to specific file |
--verbose | Full turn-by-turn output |
--version, -v | Print version |
--bare | Minimal 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. |
--init | Run Setup hooks with init matcher before session (print mode) |
--init-only | Run Setup + SessionStart hooks, then exit |
--maintenance | Run Setup hooks with maintenance matcher (print mode) |
--no-session-persistence | Don’t save session to disk (print mode) |
--disable-slash-commands | Disable all skills and commands for this session |
--chrome / --no-chrome | Toggle Chrome browser integration |
--ide | Auto-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:
| Mode | Behavior |
|---|---|
default | Standard permission prompts |
acceptEdits | Auto-accept file edits + common filesystem commands in cwd / additionalDirectories |
plan | Plan mode — Claude analyzes and produces a plan, no writes |
auto | Auto mode — background classifier reviews commands + protected-directory writes |
dontAsk | Auto-deny permission prompts (explicitly allowed tools still work) |
bypassPermissions | Skip 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:
| Scope | Location | Shared? |
|---|---|---|
| User | ~/.claude/settings.json (Windows: %USERPROFILE%\.claude\settings.json) | No |
| Project | .claude/settings.json in project root | Yes (check into git) |
| Local | .claude/settings.local.json | No (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 IDsavailableModels— whitelist models in/modelpickeroutputStyle— output style presetlanguage— preferred response languageagent— run as named subagent at session start
Permissions
permissions.allow[]— allowed tool patternspermissions.ask[]— confirmation-required patternspermissions.deny[]— blocked patternspermissions.additionalDirectories[]— extra working directoriespermissions.defaultMode— default modeallowedHttpHookUrls[]— allowlist for HTTP hookshttpHookAllowedEnvVars[]— env vars HTTP hooks can interpolatedisableBypassPermissionsMode— block bypass modeskipDangerousModePermissionPrompt— skip bypass confirmation
Managed-only (admin)
allowedMcpServers[]/deniedMcpServers[]allowManagedHooksOnly/allowManagedMcpServersOnly/allowManagedPermissionRulesOnlyclaudeMd— org-managed CLAUDE.mdforceLoginMethod(claudeaiorconsole)forceLoginOrgUUID
Files + memory
autoMemoryEnabled(default true)autoMemoryDirectoryclaudeMdExcludes[]— glob patterns to excludeplansDirectory
UI
editorMode(normalorvim)tui(fullscreenordefault)viewMode(default,verbose,focus)autoScrollEnabled,spinnerTipsEnabled,spinnerVerbsshowTurnDuration,showThinkingSummariesprefersReducedMotionpreferredNotifChannel(auto,terminal_bell,iterm2,kitty,ghostty)syntaxHighlightingDisabled
Hooks + customization
hooks— see claude-code-hooks-deepdisableAllHooksstatusLine— custom status line (percode.claude.com/docs/en/statusline)fileSuggestion— custom@file autocomplete scriptautoMode— auto-mode classifier rules
Env + creds
env— env vars set for all sessionsapiKeyHelper— script that returns API keyawsCredentialExport/awsAuthRefresh/gcpAuthRefreshotelHeadersHelper— dynamic OTel headers
Git + dev
attribution— commit/PR attribution customizationincludeCoAuthoredBy(deprecated; useattribution)includeGitInstructions(default true)prUrlTemplaterespectGitignore(default true)
Updates
autoUpdatesChannel(stableorlatest)minimumVersion
Worktree
worktree.baseRef(freshorhead)worktree.symlinkDirectories[]worktree.sparsePaths[]worktree.bgIsolation(worktreeornone)
Sandbox (per code.claude.com/docs/en/sandbox)
sandbox.enabled(default false)sandbox.failIfUnavailablesandbox.autoAllowBashIfSandboxedsandbox.excludedCommands[]sandbox.allowUnsandboxedCommandssandbox.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)enableAllProjectMcpServersenabledMcpjsonServers[]/disabledMcpjsonServers[]
Other
companyAnnouncementsdefaultShell(bashorpowershell)cleanupPeriodDays(default 30, min 1)awaySummaryEnabledfeedbackSurveyRatedisableAgentView,disableAutoMode,disableDeepLinkRegistration,disableRemoteControl,disableSkillShellExecutionparentSettingsBehavior(first-winsormerge)
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_prAgent(name)— restrict which subagents the agent tool can invokeSkill(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 keyANTHROPIC_AUTH_TOKEN— alternate auth token (Bearer)ANTHROPIC_BASE_URL— custom endpoint (proxies / Foundry-style routes)ANTHROPIC_MODEL— default modelANTHROPIC_SMALL_FAST_MODEL— model for fast operations (statusline, etc.)
Cloud providers
CLAUDE_CODE_USE_BEDROCK=1+AWS_PROFILE/AWS_REGIONetc.CLAUDE_CODE_USE_VERTEX=1+GOOGLE_APPLICATION_CREDENTIALS+GCLOUD_PROJECTCLAUDE_CODE_USE_FOUNDRY=1+ Azure credsCLAUDE_CODE_USE_ANTHROPIC_AWS=1+ANTHROPIC_AWS_WORKSPACE_ID
Behavior
CLAUDE_CODE_ENABLE_TELEMETRY/CLAUDE_CODE_DISABLE_TELEMETRYCLAUDE_CODE_DISABLE_THINKING— force thinking offCLAUDE_CODE_DISABLE_AUTO_MEMORYCLAUDE_CODE_DISABLE_AGENT_VIEWCLAUDE_CODE_DISABLE_FEEDBACK_SURVEYCLAUDE_CODE_ENABLE_AWAY_SUMMARYCLAUDE_CODE_NO_FLICKER— use fullscreen rendererCLAUDE_CODE_EFFORT_LEVELCLAUDE_CODE_USE_POWERSHELL_TOOL— enable PowerShell tool on WindowsCLAUDE_CODE_AUTO_CONNECT_IDECLAUDE_CODE_IDE_SKIP_AUTO_INSTALLCLAUDE_CODE_API_KEY_HELPER_TTL_MSCLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MSCLAUDE_CODE_SKIP_PROMPT_HISTORY— disable transcript writesCLAUDE_CODE_SIMPLE=1— set by--bareCLAUDE_CODE_MAX_OUTPUT_TOKENS— cap output tokens per requestCLAUDE_CODE_SUBAGENT_MODEL— override subagent model regardless of definitionCLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1— load CLAUDE.md from--add-dirpathsDISABLE_AUTOUPDATERCLAUDE_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 environmentsCLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX— prefix for auto-generated remote-control session names
OpenTelemetry
OTEL_METRICS_EXPORTER(otlp, etc.)OTEL_EXPORTER_OTLP_ENDPOINTOTEL_EXPORTER_OTLP_HEADERS
UI / shell
NO_COLOR/FORCE_COLORTERM
8. Slash commands
Per code.claude.com/docs/en/commands. Built-in commands available in any session:
| Command | Purpose |
|---|---|
/help | Show help |
/clear | Clear conversation context |
/compact | Compact (summarize older messages) |
/cost | Show session cost |
/init | Initialize CLAUDE.md for project (bundled skill) |
/login / /logout | Auth management |
/memory | Edit CLAUDE.md / auto-memory |
/model | Change model |
/agent / /agents | Subagent management UI |
/skills | Skills manager |
/mcp | MCP server management |
/permissions | Edit permission rules |
/hooks | Hooks management |
/statusline | Configure statusline |
/add-dir <path> | Add working directory |
/resume / /rename | Session management |
/status | Session status |
/review | Bundled skill: code review |
/pr-comments | Address PR comments |
/export | Export conversation |
/ide | IDE management |
/vim | Vim mode |
/desktop | Hand off session to desktop app |
/loop <interval> /skill | Repeat a skill on interval (bundled) |
/schedule | Create routine (cron-style) |
/teleport | Pull web session into terminal |
/run, /verify, /run-skill-generator | Bundled launch + verify skills |
/debug, /batch, /code-review, /claude-api, /security-review | Other 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 inarguments: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:
- CLI flag (
--model, etc.) - Environment variable (
ANTHROPIC_API_KEYetc.) apiKeyHelperscript in settingsclaude.aisession (/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 --continuefinds most recent session in cwdclaude --resumeshows 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 withclaude 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 IDclaude agentsopens monitor UIclaude 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 categoriesclaude --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