Skip to Content
CLI ReferenceCli

CLI Reference

Overview

The Claude Code CLI (Command Line Interface) is the primary way to interact with Claude Code. It provides powerful options for running queries, managing sessions, configuring models, and integrating Claude into your development workflows.

Architecture

CLI Commands

CommandDescriptionExample
claudeStart interactive REPLclaude
claude "query"Start REPL with initial promptclaude "explain this project"
claude -p "query"Print mode - query then exitclaude -p "explain this function"
cat file | claude -p "query"Process piped contentcat logs.txt | claude -p "explain"
claude -cContinue most recent conversationclaude -c
claude -c -p "query"Continue in print modeclaude -c -p "check for type errors"
claude -r "<session>" "query"Resume session by ID or nameclaude -r "auth-refactor" "finish this PR"
claude updateUpdate to latest versionclaude update
claude mcpConfigure MCP serversSee MCP documentation
claude mcp serveRun Claude Code as an MCP serverclaude mcp serve
claude agentsList all configured subagentsclaude agents
claude auto-mode defaultsPrint auto mode default rules as JSONclaude auto-mode defaults
claude remote-controlStart Remote Control serverclaude remote-control
claude pluginManage plugins (install, enable, disable)claude plugin install my-plugin
claude auth loginLog in (supports --email, --sso)claude auth login --email user@example.com
claude auth logoutLog out of current accountclaude auth logout
claude auth statusCheck auth status (exit 0 if logged in, 1 if not)claude auth status

Core Flags

FlagDescriptionExample
-p, --printPrint response without interactive modeclaude -p "query"
-c, --continueLoad most recent conversationclaude --continue
-r, --resumeResume specific session by ID or nameclaude --resume auth-refactor
-v, --versionOutput version numberclaude -v
-w, --worktreeStart in isolated git worktreeclaude -w
-n, --nameSession display nameclaude -n "auth-refactor"
--from-pr <number>Resume sessions linked to GitHub PRclaude --from-pr 42
--remote "task"Create web session on claude.aiclaude --remote "implement API"
--remote-control, --rcInteractive session with Remote Controlclaude --rc
--teleportResume web session locallyclaude --teleport
--teammate-modeAgent team display modeclaude --teammate-mode tmux
--bareMinimal mode (skip hooks, skills, plugins, MCP, auto memory, CLAUDE.md)claude --bare
--enable-auto-modeUnlock auto permission modeclaude --enable-auto-mode
--channelsSubscribe to MCP channel pluginsclaude --channels discord,telegram
--chrome / --no-chromeEnable/disable Chrome browser integrationclaude --chrome
--effortSet thinking effort levelclaude --effort high
--init / --init-onlyRun initialization hooksclaude --init
--maintenanceRun maintenance hooks and exitclaude --maintenance
--disable-slash-commandsDisable all skills and slash commandsclaude --disable-slash-commands
--no-session-persistenceDisable session saving (print mode)claude -p --no-session-persistence "query"

Interactive vs Print Mode

Interactive Mode (default):

# Start interactive session claude # Start with initial prompt claude "explain the authentication flow"

Print Mode (non-interactive):

# Single query, then exit claude -p "what does this function do?" # Process file content cat error.log | claude -p "explain this error" # Chain with other tools claude -p "list todos" | grep "URGENT"

Model & Configuration

FlagDescriptionExample
--modelSet model (sonnet, opus, haiku, or full name)claude --model opus
--fallback-modelAutomatic model fallback when overloadedclaude -p --fallback-model sonnet "query"
--agentSpecify agent for sessionclaude --agent my-custom-agent
--agentsDefine custom subagents via JSONSee Agents Configuration
--effortSet effort level (low, medium, high, max)claude --effort high

Model Selection Examples

# Use Opus 4.6 for complex tasks claude --model opus "design a caching strategy" # Use Haiku 4.5 for quick tasks claude --model haiku -p "format this JSON" # Full model name claude --model claude-sonnet-4-6-20250929 "review this code" # With fallback for reliability claude -p --model opus --fallback-model sonnet "analyze architecture" # Use opusplan (Opus plans, Sonnet executes) claude --model opusplan "design and implement the caching layer"

System Prompt Customization

FlagDescriptionExample
--system-promptReplace entire default promptclaude --system-prompt "You are a Python expert"
--system-prompt-fileLoad prompt from file (print mode)claude -p --system-prompt-file ./prompt.txt "query"
--append-system-promptAppend to default promptclaude --append-system-prompt "Always use TypeScript"

System Prompt Examples

# Complete custom persona claude --system-prompt "You are a senior security engineer. Focus on vulnerabilities." # Append specific instructions claude --append-system-prompt "Always include unit tests with code examples" # Load complex prompt from file claude -p --system-prompt-file ./prompts/code-reviewer.txt "review main.py"

System Prompt Flags Comparison

FlagBehaviorInteractivePrint
--system-promptReplaces entire default system prompt
--system-prompt-fileReplaces with prompt from file
--append-system-promptAppends to default system prompt

Use --system-prompt-file only in print mode. For interactive mode, use --system-prompt or --append-system-prompt.

Tool & Permission Management

FlagDescriptionExample
--toolsRestrict available built-in toolsclaude -p --tools "Bash,Edit,Read" "query"
--allowedToolsTools that execute without prompting"Bash(git log:*)" "Read"
--disallowedToolsTools removed from context"Bash(rm:*)" "Edit"
--dangerously-skip-permissionsSkip all permission promptsclaude --dangerously-skip-permissions
--permission-modeBegin in specified permission modeclaude --permission-mode auto
--permission-prompt-toolMCP tool for permission handlingclaude -p --permission-prompt-tool mcp_auth "query"
--enable-auto-modeUnlock auto permission modeclaude --enable-auto-mode

Permission Examples

# Read-only mode for code review claude --permission-mode plan "review this codebase" # Restrict to safe tools only claude --tools "Read,Grep,Glob" -p "find all TODO comments" # Allow specific git commands without prompts claude --allowedTools "Bash(git status:*)" "Bash(git log:*)" # Block dangerous operations claude --disallowedTools "Bash(rm -rf:*)" "Bash(git push --force:*)"

Output & Format

FlagDescriptionOptionsExample
--output-formatSpecify output format (print mode)text, json, stream-jsonclaude -p --output-format json "query"
--input-formatSpecify input format (print mode)text, stream-jsonclaude -p --input-format stream-json
--verboseEnable verbose loggingclaude --verbose
--include-partial-messagesInclude streaming eventsRequires stream-jsonclaude -p --output-format stream-json --include-partial-messages "query"
--json-schemaGet validated JSON matching schemaclaude -p --json-schema '{"type":"object"}' "query"
--max-budget-usdMaximum spend for print modeclaude -p --max-budget-usd 5.00 "query"

Output Format Examples

# Plain text (default) claude -p "explain this code" # JSON for programmatic use claude -p --output-format json "list all functions in main.py" # Streaming JSON for real-time processing claude -p --output-format stream-json "generate a long report" # Structured output with schema validation claude -p --json-schema '{"type":"object","properties":{"bugs":{"type":"array"}}}' \ "find bugs in this code and return as JSON"

Workspace & Directory

FlagDescriptionExample
--add-dirAdd additional working directoriesclaude --add-dir ../apps ../lib
--setting-sourcesComma-separated setting sourcesclaude --setting-sources user,project
--settingsLoad settings from file or JSONclaude --settings ./settings.json
--plugin-dirLoad plugins from directory (repeatable)claude --plugin-dir ./my-plugin

Multi-Directory Example

# Work across multiple project directories claude --add-dir ../frontend ../backend ../shared "find all API endpoints" # Load custom settings claude --settings '{"model":"opus","verbose":true}' "complex task"

MCP Configuration

FlagDescriptionExample
--mcp-configLoad MCP servers from JSONclaude --mcp-config ./mcp.json
--strict-mcp-configOnly use specified MCP configclaude --strict-mcp-config --mcp-config ./mcp.json
--channelsSubscribe to MCP channel pluginsclaude --channels discord,telegram

MCP Examples

# Load GitHub MCP server claude --mcp-config ./github-mcp.json "list open PRs" # Strict mode - only specified servers claude --strict-mcp-config --mcp-config ./production-mcp.json "deploy to staging"

Session Management

FlagDescriptionExample
--session-idUse specific session ID (UUID)claude --session-id "550e8400-..."
--fork-sessionCreate new session when resumingclaude --resume abc123 --fork-session

Session Examples

# Continue last conversation claude -c # Resume named session claude -r "feature-auth" "continue implementing login" # Fork session for experimentation claude --resume feature-auth --fork-session "try alternative approach" # Use specific session ID claude --session-id "550e8400-e29b-41d4-a716-446655440000" "continue"

Session Fork

Create a branch from an existing session for experimentation:

# Fork a session to try a different approach claude --resume abc123 --fork-session "try alternative implementation" # Fork with a custom message claude -r "feature-auth" --fork-session "test with different architecture"

Use Cases:

  • Try alternative implementations without losing the original session
  • Experiment with different approaches in parallel
  • Create branches from successful work for variations
  • Test breaking changes without affecting the main session

The original session remains unchanged, and the fork becomes a new independent session.

Advanced Features

FlagDescriptionExample
--chromeEnable Chrome browser integrationclaude --chrome
--no-chromeDisable Chrome browser integrationclaude --no-chrome
--ideAuto-connect to IDE if availableclaude --ide
--max-turnsLimit agentic turns (non-interactive)claude -p --max-turns 3 "query"
--debugEnable debug mode with filteringclaude --debug "api,mcp"
--enable-lsp-loggingEnable verbose LSP loggingclaude --enable-lsp-logging
--betasBeta headers for API requestsclaude --betas interleaved-thinking
--plugin-dirLoad plugins from directory (repeatable)claude --plugin-dir ./my-plugin
--enable-auto-modeUnlock auto permission modeclaude --enable-auto-mode
--effortSet thinking effort levelclaude --effort high
--bareMinimal mode (skip hooks, skills, plugins, MCP, auto memory, CLAUDE.md)claude --bare
--channelsSubscribe to MCP channel pluginsclaude --channels discord
--fork-sessionCreate new session ID when resumingclaude --resume abc --fork-session
--max-budget-usdMaximum spend (print mode)claude -p --max-budget-usd 5.00 "query"
--json-schemaValidated JSON outputclaude -p --json-schema '{"type":"object"}' "q"

Advanced Examples

# Limit autonomous actions claude -p --max-turns 5 "refactor this module" # Debug API calls claude --debug "api" "test query" # Enable IDE integration claude --ide "help me with this file"

Agents Configuration

The --agents flag accepts a JSON object defining custom subagents for a session.

Agents JSON Format

{ "agent-name": { "description": "Required: when to invoke this agent", "prompt": "Required: system prompt for the agent", "tools": ["Optional", "array", "of", "tools"], "model": "optional: sonnet|opus|haiku" } }

Required Fields:

  • description - Natural language description of when to use this agent
  • prompt - System prompt that defines the agent’s role and behavior

Optional Fields:

  • tools - Array of available tools (inherits all if omitted)
    • Format: ["Read", "Grep", "Glob", "Bash"]
  • model - Model to use: sonnet, opus, or haiku

Complete Agents Example

{ "code-reviewer": { "description": "Expert code reviewer. Use proactively after code changes.", "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.", "tools": ["Read", "Grep", "Glob", "Bash"], "model": "sonnet" }, "debugger": { "description": "Debugging specialist for errors and test failures.", "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes.", "tools": ["Read", "Edit", "Bash", "Grep"], "model": "opus" }, "documenter": { "description": "Documentation specialist for generating guides.", "prompt": "You are a technical writer. Create clear, comprehensive documentation.", "tools": ["Read", "Write"], "model": "haiku" } }

Agents Command Examples

# Define custom agents inline claude --agents '{ "security-auditor": { "description": "Security specialist for vulnerability analysis", "prompt": "You are a security expert. Find vulnerabilities and suggest fixes.", "tools": ["Read", "Grep", "Glob"], "model": "opus" } }' "audit this codebase for security issues" # Load agents from file claude --agents "$(cat ~/.claude/agents.json)" "review the auth module" # Combine with other flags claude -p --agents "$(cat agents.json)" --model sonnet "analyze performance"

Agent Priority

When multiple agent definitions exist, they are loaded in this priority order:

  1. CLI-defined (--agents flag) - Session-specific
  2. User-level (~/.claude/agents/) - All projects
  3. Project-level (.claude/agents/) - Current project

CLI-defined agents override both user and project agents for the session.


High-Value Use Cases

1. CI/CD Integration

Use Claude Code in your CI/CD pipelines for automated code review, testing, and documentation.

GitHub Actions Example:

name: AI Code Review on: [pull_request] jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Claude Code run: npm install -g @anthropic-ai/claude-code - name: Run Code Review env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} run: | claude -p --output-format json \ --max-turns 1 \ "Review the changes in this PR for: - Security vulnerabilities - Performance issues - Code quality Output as JSON with 'issues' array" > review.json - name: Post Review Comment uses: actions/github-script@v7 with: script: | const fs = require('fs'); const review = JSON.parse(fs.readFileSync('review.json', 'utf8')); // Process and post review comments

Jenkins Pipeline:

pipeline { agent any stages { stage('AI Review') { steps { sh ''' claude -p --output-format json \ --max-turns 3 \ "Analyze test coverage and suggest missing tests" \ > coverage-analysis.json ''' } } } }

2. Script Piping

Process files, logs, and data through Claude for analysis.

Log Analysis:

# Analyze error logs tail -1000 /var/log/app/error.log | claude -p "summarize these errors and suggest fixes" # Find patterns in access logs cat access.log | claude -p "identify suspicious access patterns" # Analyze git history git log --oneline -50 | claude -p "summarize recent development activity"

Code Processing:

# Review a specific file cat src/auth.ts | claude -p "review this authentication code for security issues" # Generate documentation cat src/api/*.ts | claude -p "generate API documentation in markdown" # Find TODOs and prioritize grep -r "TODO" src/ | claude -p "prioritize these TODOs by importance"

3. Multi-Session Workflows

Manage complex projects with multiple conversation threads.

# Start a feature branch session claude -r "feature-auth" "let's implement user authentication" # Later, continue the session claude -r "feature-auth" "add password reset functionality" # Fork to try an alternative approach claude --resume feature-auth --fork-session "try OAuth instead" # Switch between different feature sessions claude -r "feature-payments" "continue with Stripe integration"

4. Custom Agent Configuration

Define specialized agents for your team’s workflows.

# Save agents config to file cat > ~/.claude/agents.json << 'EOF' { "reviewer": { "description": "Code reviewer for PR reviews", "prompt": "Review code for quality, security, and maintainability.", "model": "opus" }, "documenter": { "description": "Documentation specialist", "prompt": "Generate clear, comprehensive documentation.", "model": "sonnet" }, "refactorer": { "description": "Code refactoring expert", "prompt": "Suggest and implement clean code refactoring.", "tools": ["Read", "Edit", "Glob"] } } EOF # Use agents in session claude --agents "$(cat ~/.claude/agents.json)" "review the auth module"

5. Batch Processing

Process multiple queries with consistent settings.

# Process multiple files for file in src/*.ts; do echo "Processing $file..." claude -p --model haiku "summarize this file: $(cat $file)" >> summaries.md done # Batch code review find src -name "*.py" -exec sh -c ' echo "## $1" >> review.md cat "$1" | claude -p "brief code review" >> review.md ' _ {} \; # Generate tests for all modules for module in $(ls src/modules/); do claude -p "generate unit tests for src/modules/$module" > "tests/$module.test.ts" done

6. Security-Conscious Development

Use permission controls for safe operation.

# Read-only security audit claude --permission-mode plan \ --tools "Read,Grep,Glob" \ "audit this codebase for security vulnerabilities" # Block dangerous commands claude --disallowedTools "Bash(rm:*)" "Bash(curl:*)" "Bash(wget:*)" \ "help me clean up this project" # Restricted automation claude -p --max-turns 2 \ --allowedTools "Read" "Glob" \ "find all hardcoded credentials"

7. JSON API Integration

Use Claude as a programmable API for your tools with jq parsing.

# Get structured analysis claude -p --output-format json \ --json-schema '{"type":"object","properties":{"functions":{"type":"array"},"complexity":{"type":"string"}}}' \ "analyze main.py and return function list with complexity rating" # Integrate with jq for processing claude -p --output-format json "list all API endpoints" | jq '.endpoints[]' # Use in scripts RESULT=$(claude -p --output-format json "is this code secure? answer with {secure: boolean, issues: []}" < code.py) if echo "$RESULT" | jq -e '.secure == false' > /dev/null; then echo "Security issues found!" echo "$RESULT" | jq '.issues[]' fi

jq Parsing Examples

Parse and process Claude’s JSON output using jq:

# Extract specific fields claude -p --output-format json "analyze this code" | jq '.result' # Filter array elements claude -p --output-format json "list issues" | jq -r '.issues[] | select(.severity=="high")' # Extract multiple fields claude -p --output-format json "describe the project" | jq -r '.{name, version, description}' # Convert to CSV claude -p --output-format json "list functions" | jq -r '.functions[] | [.name, .lineCount] | @csv' # Conditional processing claude -p --output-format json "check security" | jq 'if .vulnerabilities | length > 0 then "UNSAFE" else "SAFE" end' # Extract nested values claude -p --output-format json "analyze performance" | jq '.metrics.cpu.usage' # Process entire array claude -p --output-format json "find todos" | jq '.todos | length' # Transform output claude -p --output-format json "list improvements" | jq 'map({title: .title, priority: .priority})'

Models

Claude Code supports multiple models with different capabilities:

ModelIDContext WindowNotes
Opus 4.6claude-opus-4-61M tokensMost capable, adaptive effort levels
Sonnet 4.6claude-sonnet-4-61M tokensBalanced speed and capability
Haiku 4.5claude-haiku-4-51M tokensFastest, best for quick tasks

Model Selection

# Use short names claude --model opus "complex architectural review" claude --model sonnet "implement this feature" claude --model haiku -p "format this JSON" # Use opusplan alias (Opus plans, Sonnet executes) claude --model opusplan "design and implement the API" # Toggle fast mode during session /fast

Effort Levels (Opus 4.6)

Opus 4.6 supports adaptive reasoning with effort levels:

# Set effort level via CLI flag claude --effort high "complex review" # Set effort level via slash command /effort high # Set effort level via environment variable export CLAUDE_CODE_EFFORT_LEVEL=high # low, medium, high, or max (Opus 4.6 only)

The “ultrathink” keyword in prompts activates deep reasoning. The max effort level is exclusive to Opus 4.6.


Key Environment Variables

VariableDescription
ANTHROPIC_API_KEYAPI key for authentication
ANTHROPIC_MODELOverride default model
ANTHROPIC_CUSTOM_MODEL_OPTIONCustom model option for API
ANTHROPIC_DEFAULT_OPUS_MODELOverride default Opus model ID
ANTHROPIC_DEFAULT_SONNET_MODELOverride default Sonnet model ID
ANTHROPIC_DEFAULT_HAIKU_MODELOverride default Haiku model ID
MAX_THINKING_TOKENSSet extended thinking token budget
CLAUDE_CODE_EFFORT_LEVELSet effort level (low/medium/high/max)
CLAUDE_CODE_SIMPLEMinimal mode, set by --bare flag
CLAUDE_CODE_DISABLE_AUTO_MEMORYDisable automatic CLAUDE.md updates
CLAUDE_CODE_DISABLE_BACKGROUND_TASKSDisable background task execution
CLAUDE_CODE_DISABLE_CRONDisable scheduled/cron tasks
CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONSDisable git-related instructions
CLAUDE_CODE_DISABLE_TERMINAL_TITLEDisable terminal title updates
CLAUDE_CODE_DISABLE_1M_CONTEXTDisable 1M token context window
CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACKDisable non-streaming fallback
CLAUDE_CODE_ENABLE_TASKSEnable task list feature
CLAUDE_CODE_TASK_LIST_IDNamed task directory shared across sessions
CLAUDE_CODE_ENABLE_PROMPT_SUGGESTIONToggle prompt suggestions (true/false)
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMSEnable experimental agent teams
CLAUDE_CODE_NEW_INITUse new initialization flow
CLAUDE_CODE_SUBAGENT_MODELModel for subagent execution
CLAUDE_CODE_PLUGIN_SEED_DIRDirectory for plugin seed files
CLAUDE_CODE_SUBPROCESS_ENV_SCRUBEnv vars to scrub from subprocesses
CLAUDE_AUTOCOMPACT_PCT_OVERRIDEOverride auto-compaction percentage
CLAUDE_STREAM_IDLE_TIMEOUT_MSStream idle timeout in milliseconds
SLASH_COMMAND_TOOL_CHAR_BUDGETCharacter budget for slash command tools
ENABLE_TOOL_SEARCHEnable tool search capability
MAX_MCP_OUTPUT_TOKENSMaximum tokens for MCP tool output

Quick Reference

Most Common Commands

# Interactive session claude # Quick question claude -p "how do I..." # Continue conversation claude -c # Process a file cat file.py | claude -p "review this" # JSON output for scripts claude -p --output-format json "query"

Flag Combinations

Use CaseCommand
Quick code review`cat file
Structured outputclaude -p --output-format json "query"
Safe explorationclaude --permission-mode plan
Autonomous with safetyclaude --enable-auto-mode --permission-mode auto
CI/CD integrationclaude -p --max-turns 3 --output-format json
Resume workclaude -r "session-name"
Custom modelclaude --model opus "complex task"
Minimal modeclaude --bare "quick query"
Budget-capped runclaude -p --max-budget-usd 2.00 "analyze code"

Troubleshooting

Command Not Found

Problem: claude: command not found

Solutions:

  • Install Claude Code: npm install -g @anthropic-ai/claude-code
  • Check PATH includes npm global bin directory
  • Try running with full path: npx claude

API Key Issues

Problem: Authentication failed

Solutions:

  • Set API key: export ANTHROPIC_API_KEY=your-key
  • Check key is valid and has sufficient credits
  • Verify key permissions for the model requested

Session Not Found

Problem: Cannot resume session

Solutions:

  • List available sessions to find correct name/ID
  • Sessions may expire after period of inactivity
  • Use -c to continue most recent session

Output Format Issues

Problem: JSON output is malformed

Solutions:

  • Use --json-schema to enforce structure
  • Add explicit JSON instructions in prompt
  • Use --output-format json (not just asking for JSON in prompt)

Permission Denied

Problem: Tool execution blocked

Solutions:

  • Check --permission-mode setting
  • Review --allowedTools and --disallowedTools flags
  • Use --dangerously-skip-permissions for automation (with caution)

Additional Resources


Part of the Claude How To guide series

Last updated on