NEW: Claude Code Security — research preview →

Claude Code CLI Reference

Complete reference for claude CLI flags, --allowedTools, --output-format, environment variables, and settings.json

CLIRead time: 13 min

title: "Claude Code CLI Reference" description: "Complete reference for claude CLI flags, --allowedTools, --output-format, environment variables, and settings.json" section: "Reference" readTime: "13 min" badge: "CLI"

Claude Code CLI Reference

Complete reference for the claude command-line tool.

Installation

The native installer is the recommended method and auto-updates in the background:

# macOS, Linux, WSL
curl -fsSL https://claude.ai/install.sh | bash
 
# Windows PowerShell
irm https://claude.ai/install.ps1 | iex
 
claude --version

Alternatives: brew install --cask claude-code (Homebrew), winget install Anthropic.ClaudeCode (WinGet), or npm install -g @anthropic-ai/claude-code (requires Node.js 22+; never use sudo). Homebrew and WinGet installs do not auto-update.

Authentication:

claude auth login    # OAuth flow (use --console for API billing)
claude auth status   # check login state (JSON; --text for readable output)
# or set env var:
export ANTHROPIC_API_KEY=sk-ant-...

Claude Code requires a Pro, Max, Team, Enterprise, or Console account (the free claude.ai plan does not include it), or a third-party provider such as Amazon Bedrock.


Core Flags

--print / -p

Non-interactive mode. Print the response and exit. Required for scripting and CI.

claude -p "Explain what this function does" < src/auth.ts
echo "Review this diff for bugs" | claude -p

--output-format

Control response format in print mode. Options: text (default), json, stream-json.

# JSON output for scripting (text answer is in the "result" field)
claude -p --output-format json "List all API endpoints in this project"
 
# Streaming JSON (newline-delimited events) for real-time processing
claude -p --output-format stream-json --verbose "Generate 50 test cases for the auth module"

For output that must match a schema, add --json-schema '<schema>'; the validated object appears in the structured_output field.

--model

Override the model for this session. Accepts an alias (opus, sonnet, haiku, fable, opusplan) or a full model ID.

claude --model opus "Design the database schema..."
claude --model sonnet "Fix this bug..."
claude --model claude-opus-5-5 "..."   # full model ID

On the Anthropic API and Pro/Max/Team/Enterprise plans, the default model is Opus 5.5. Mid-session, switch with /model.

--effort

Set the effort level for the session: low, medium, high, xhigh, max (available levels depend on the model). Does not persist.

claude --effort high "Find the race condition in the job queue"

Limiting output length

There is no --max-tokens flag. To cap output tokens, set the CLAUDE_CODE_MAX_OUTPUT_TOKENS environment variable. To cap spend in scripted runs, use --max-budget-usd (print mode only):

claude -p --max-budget-usd 2.00 "Write a one-paragraph summary of README.md"

--max-turns

Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default.

claude -p --max-turns 10 "Refactor the auth module"

--allowedTools

Tools that execute without prompting for permission. Accepts tool names or permission rules, each as its own quoted argument. This pre-approves tools; it does not remove the others.

# Auto-approve git inspection commands and file reads
claude "Summarize this week's changes" --allowedTools "Bash(git log *)" "Bash(git diff *)" "Read"
 
# Auto-approve edits in a headless run
claude -p "Fix the typos in docs/" --allowedTools "Read" "Edit"

Because --allowedTools, --disallowedTools, and --add-dir take multiple values, put your prompt before them so it isn't read as another tool name.

--tools

Restrict which built-in tools Claude can use at all. Use "" to disable all, "default" for the default set, or a list of names. Does not affect MCP tools.

# Read-only audit — no writes or shell commands available
claude --tools "Read,Glob,Grep" "Audit all API routes for missing auth checks"

Common built-in tool names: Read, Write, Edit, Bash, Glob, Grep, WebFetch, WebSearch, Agent (subagents, formerly Task), TodoWrite, NotebookEdit, Skill. On native Windows a PowerShell tool may be available too.

On macOS, Linux, and WSL, the default tool set leaves out Glob and Grep (Claude searches through Bash instead). Name them explicitly in --tools if you want them.

--disallowedTools

Deny rules. A bare tool name removes that tool from Claude's context; a scoped rule denies only matching calls.

# Remove shell access entirely
claude "Refactor the auth module" --disallowedTools "Bash"
 
# Keep Bash, but block destructive commands
claude "Clean up the build scripts" --disallowedTools "Bash(rm *)"

--permission-mode

Start in a specific permission mode: default, acceptEdits, plan, auto, dontAsk, or bypassPermissions. Overrides defaultMode from settings. During a session, Shift+Tab cycles modes.

claude --permission-mode plan "Add OAuth2 authentication"
# Claude researches and proposes a plan without editing files.
# Approve the plan in the session to let it start implementing.

--dangerously-skip-permissions

Skip permission prompts. Equivalent to --permission-mode bypassPermissions.

claude --dangerously-skip-permissions "Run all tests and fix any failures"

Only use in sandboxed environments (Docker, CI). This flag allows the agent to execute any shell command, modify any file, and perform any action without confirmation.

--continue / -c and --resume / -r

Continue the most recent conversation in the current directory, or resume a specific session by ID or name. With no argument, --resume opens an interactive picker.

claude -c                         # continue most recent conversation
claude --resume                   # pick from recent sessions
claude --resume auth-refactor     # resume by name or ID
claude -n "auth-refactor"         # name a new session so you can resume it later
claude --resume abc123 --fork-session   # branch into a new session ID

--verbose

Enable verbose logging with full turn-by-turn output.

claude --verbose "Implement the user service"

--debug

Enable debug mode, optionally filtered by category. Use --debug-file <path> to write logs to a file.

claude --debug='mcp,startup'

Other useful flags

FlagPurpose
--add-dir <paths>Give Claude file access to additional directories
--append-system-prompt "..."Append text to the default system prompt (--append-system-prompt-file reads from a file)
--system-prompt "..."Replace the entire system prompt (--system-prompt-file reads from a file)
--mcp-config <file>Load MCP servers from JSON files or strings; add --strict-mcp-config to ignore all others
--settings <file-or-json>Load extra settings for this session
--agents '<json>'Define subagents inline as JSON
--agent <name>Run the session as a specific agent
--worktree / -w <name>Start in an isolated git worktree under .claude/worktrees/
--bareMinimal mode for scripts: skip hooks, skills, plugins, MCP, CLAUDE.md, and auto memory discovery
--fallback-model <models>Fall back to other models when the primary is overloaded
--input-format stream-jsonAccept streaming JSON input in print mode
--no-session-persistenceDon't save the session to disk (print mode only)
--version / -vPrint the version

Environment Variables

VariableDescription
ANTHROPIC_API_KEYAPI key for authentication (overrides your subscription when set)
ANTHROPIC_AUTH_TOKENCustom Authorization header value (sent as Bearer ...)
ANTHROPIC_BASE_URLOverride the API endpoint to route through a proxy or gateway
ANTHROPIC_MODELDefault model override
CLAUDE_CODE_MAX_OUTPUT_TOKENSMaximum output tokens for most requests
CLAUDE_CODE_OAUTH_TOKENOAuth token for CI/scripts (generate with claude setup-token)
CLAUDE_CODE_USE_BEDROCK / CLAUDE_CODE_USE_VERTEXUse Amazon Bedrock / Google Cloud's Agent Platform
BASH_DEFAULT_TIMEOUT_MSDefault Bash command timeout (default 120000)
CLAUDE_CONFIG_DIRStore settings, history, and plugins somewhere other than ~/.claude
DISABLE_AUTOUPDATERSet to 1 to stop background auto-updates

Settings File (settings.json)

ScopeLocationApplies to
User~/.claude/settings.jsonYou, in every project
Project.claude/settings.jsonEveryone on the project (commit it)
Local.claude/settings.local.jsonYou, in this project (git-ignored)
Managedmanaged-settings.json / MDM / admin consoleYour organization; cannot be overridden

Precedence, highest first: managed, command-line --settings, local, project, user.

{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "model": "opus",
 
  "permissions": {
    "allow": [
      "Bash(npm test)",
      "Bash(npm run lint)",
      "Edit(src/**)",
      "Read(**)"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(git push *)",
      "Read(./.env)"
    ]
  },
 
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{
          "type": "command",
          "command": "jq -r '.tool_input.command' >> ~/.claude/audit.log"
        }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{
          "type": "command",
          "command": "jq -r '.tool_input.file_path' | xargs npx eslint --fix 2>/dev/null || true"
        }]
      }
    ]
  },
 
  "env": {
    "NODE_ENV": "development"
  }
}

Settings files are strict JSON: comments and trailing commas are errors. Hooks receive the event as JSON on stdin (for example tool_input.command or tool_input.file_path), not as environment variables, so the examples above parse it with jq.

Permission Pattern Syntax

PatternMatches
BashAll bash commands
Bash(npm *)Bash commands starting with npm (Bash(npm:*) is equivalent)
Bash(npm test)Exactly npm test
Edit(src/**)Edits to files under src/ (relative to current directory)
Edit(/src/**)Paths relative to the settings file's project root
Read(~/Documents/*.pdf)Paths relative to your home directory
Read(//etc/**)Absolute filesystem path (note the double slash)
Read(**)All file reads

Rules are evaluated deny first, then ask, then allow.


Common Recipes

Safe Audit (Read-Only)

claude --tools "Read,Glob,Grep" \
  "Audit all API routes in src/routes/ for missing authentication middleware. 
   Report file, line number, and the missing check."

Batch Documentation

find src/lib -name "*.ts" | while read f; do
  claude -p "Add JSDoc to all exported functions in $f that lack documentation" \
    --allowedTools "Read" "Edit"
done

CI Security Scan

git diff origin/main...HEAD | \
  claude -p --output-format json \
    "Scan for: hardcoded secrets, SQL injection, missing input validation. 
     Return JSON array: [{file, line, severity, issue}]" \
  | jq -r '.result'

Autonomous Test Generation

claude -p --dangerously-skip-permissions \
  --max-turns 30 \
  "Generate Jest tests for all functions in src/utils/ that currently have &lt;60% coverage.
   Run npm run test:coverage after each file to verify. Commit changes when done."

Subcommands

claude "query"                # Start interactive session with an initial prompt
claude update                 # Update to latest version
claude install stable         # Install/reinstall a version or channel
claude doctor                 # Installation and settings diagnostics
claude auth login             # Authenticate
claude auth logout            # Remove credentials
claude auth status            # Show auth status
claude setup-token            # Long-lived OAuth token for CI (subscription required)
claude mcp                    # Configure MCP servers
claude plugin                 # Manage plugins
claude agents                 # Agent view for parallel background sessions

There is no claude sessions or claude config subcommand: use claude --resume to find past sessions and /config inside a session (or edit settings.json) to change settings.