Claude Code CLI Reference: Every Command and Flag
Complete reference for Claude Code CLI commands, flags, environment variables, and scripting patterns for automation and CI/CD.
Claude Code CLI Reference: Every Command and Flag
Key Takeaways#
claude -p "query"is the workhorse for scripting and CI/CD — it runs a one-shot query in non-interactive print mode and exits.- Permission modes (
--permission-mode) let you trade safety for automation speed: usedefaultfor interactive work,acceptEditsorautofor semi-automated runs, andbypassPermissionsonly in sandboxed CI. - Session flags (
-c,-r,--session-id) let you continue or resume conversations, enabling multi-step workflows without repeating context. - JSON output (
--output-format json) gives you structured data including cost, duration, and turn count — essential for monitoring and alerting in production pipelines. - Environment variables control provider backends (Bedrock, Vertex, Foundry), auto-updates, and API key injection — set them before any scripting.
Core Commands#
| Command | Description |
|---|---|
claude | Start an interactive REPL session |
claude "query" | Start interactive session with an initial prompt |
claude -p "query" | Print mode: run a query, print the result, exit |
claude -c | Continue the most recent conversation |
claude -r | Resume a previous session (select from list) |
claude update | Update Claude Code to the latest version |
claude install | Install or reinstall Claude Code |
claude auth login | Authenticate with your Anthropic account |
claude auth logout | Clear stored authentication credentials |
claude auth status | Show current authentication state |
claude agents | Manage and list Claude Code agents |
claude mcp | Manage MCP (Model Context Protocol) server connections |
claude plugin | Manage Claude Code plugins |
claude remote-control | Control a running Claude Code instance remotely |
claude setup-token | Configure API token for programmatic access |
Session & Interaction Flags#
| Flag | Description |
|---|---|
-p, --print | Print mode: output result and exit (non-interactive) |
-c, --continue | Continue the most recent conversation in the current directory |
-r, --resume | Resume a previous session; prompts you to select one |
-n, --name | Assign a name to the session for easier retrieval |
--session-id | Specify an exact session ID to resume |
--fork-session | Fork an existing session into a new branch |
--from-pr | Load context from a pull request URL |
--init | Initialize the project with a CLAUDE.md file |
--init-only | Only create CLAUDE.md, then exit |
--maintenance | Run in maintenance mode (reduced features) |
-v, --version | Print the CLI version |
--verbose | Enable verbose logging output |
Model & Effort Flags#
| Flag | Values | Description |
|---|---|---|
--model | sonnet, opus, or full name (e.g. claude-sonnet-4-6) | Select the model to use |
--effort | low, medium, high, xhigh, max | Control reasoning effort and token budget |
--fallback-model | Same as --model | Specify a fallback model if the primary is unavailable |
The --effort flag directly controls how much reasoning the model applies. low is fast and cheap for simple tasks; max engages deep chain-of-thought for complex problems.
Permission Flags#
| Flag | Description |
|---|---|
--permission-mode default | Standard mode: prompts for risky actions |
--permission-mode acceptEdits | Auto-accept file edits; still prompts for destructive actions |
--permission-mode plan | Read-only: plan changes without executing them |
--permission-mode auto | Auto-accept most tool calls with minimal prompting |
--permission-mode dontAsk | Attempt all actions; fail if permission is denied |
--permission-mode bypassPermissions | Skip all permission checks (dangerous — sandbox only) |
--dangerously-skip-permissions | Alias/shorthand for bypassPermissions |
--allowedTools | Comma-separated allowlist of tools the model may use |
--disallowedTools | Comma-separated blocklist of tools the model may not use |
Warning: bypassPermissions and --dangerously-skip-permissions should only be used in fully sandboxed environments (Docker containers, CI runners with no sensitive access). Never use them on a local development machine with real credentials.
Non-Interactive Mode (-p) Deep Dive#
The -p / --print flag is the foundation for all scripting and automation with Claude Code.
Basic One-Shot Query#
claude -p "Explain the purpose of the config.yaml file in this repo"
Runs the query, prints the response to stdout, and exits with code 0.
Piped Input#
cat error.log | claude -p "Analyze this error log and identify the root cause"
Pipe any content into stdin. Claude Code reads it as context before processing the prompt.
Output Formats#
| Flag | Description |
|---|---|
--output-format text | Plain text output (default) |
--output-format json | Structured JSON output |
--output-format stream-json | Streaming JSON (one object per line as turns complete) |
JSON Output Structure#
When using --output-format json, the output is a JSON object:
{ "type": "result", "subtype": "success", "total_cost_usd": 0.0042, "duration_ms": 3210, "num_turns": 2, "result": "The root cause is a missing database connection...", "session_id": "abc123-def456" }
| Field | Description |
|---|---|
type | Always "result" for completed runs |
subtype | "success" or "error" |
total_cost_usd | Total API cost in USD |
duration_ms | Wall-clock duration in milliseconds |
num_turns | Number of conversation turns |
result | The final text response |
session_id | Session identifier for follow-up with --session-id |
Turn and Bare Control#
| Flag | Description |
|---|---|
--max-turns N | Limit the conversation to N turns; exit after the limit |
--bare | Strip all formatting and framing from output |
--max-turns is critical for CI pipelines — it prevents runaway conversations from burning through your API budget.
Key Environment Variables#
| Variable | Description |
|---|---|
ANTHROPIC_API_KEY | API key for direct Anthropic API access |
CLAUDE_CODE_USE_BEDROCK | Set to 1 to route requests through AWS Bedrock |
CLAUDE_CODE_USE_VERTEX | Set to 1 to route requests through Google Vertex AI |
CLAUDE_CODE_USE_FOUNDRY | Set to 1 to route requests through Anthropic Foundry |
DISABLE_AUTOUPDATER | Set to 1 to disable automatic CLI updates |
DISABLE_UPDATES | Set to 1 to disable all update checks |
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB | Scrub sensitive env vars from subprocess calls |
Provider variables are mutually exclusive — set only one of USE_BEDROCK, USE_VERTEX, or USE_FOUNDRY. If none are set, Claude Code uses the direct Anthropic API with ANTHROPIC_API_KEY.
Scripting Patterns#
Piping Files for Analysis#
cat src/auth/errors.go | claude -p "Explain each error type and suggest better messages"
CI Integration with Structured Output#
claude -p "Review the diff and flag any security concerns" \ --output-format json \ --max-turns 5 \ --permission-mode bypassPermissions
Parse the JSON in your CI script:
RESULT=$(claude -p "..." --output-format json --max-turns 3) COST=$(echo "$RESULT" | jq -r '.total_cost_usd') DURATION=$(echo "$RESULT" | jq -r '.duration_ms') TEXT=$(echo "$RESULT" | jq -r '.result') echo "Cost: \${COST} | Duration: \${DURATION}ms"
Scheduled / Cron Tasks#
# Daily codebase health check (crontab) 0 6 * * * cd /home/user/project && claude -p "Summarize open TODOs and FIXMEs" --output-format json --max-turns 3 >> /var/log/claude-health.log
Multi-Step Workflows with Session IDs#
# Step 1: Analysis SESSION=$(claude -p "Analyze the test failures" --output-format json | jq -r '.session_id') # Step 2: Fix (continue the same session) claude -p "Now fix the failures you identified" --session-id "$SESSION"
Error Handling#
RESULT=$(claude -p "query" --output-format json --max-turns 2) SUBTYPE=$(echo "$RESULT" | jq -r '.subtype') if [ "$SUBTYPE" = "error" ]; then echo "Claude Code failed" >&2 echo "$RESULT" | jq -r '.result' >&2 exit 1 fi
Quick Reference Cheat Sheet#
# Interactive claude # start REPL claude "fix the tests" # start with prompt # One-shot claude -p "explain this file" cat file | claude -p "analyze" # Sessions claude -c # continue last claude -r # resume (pick) claude --session-id ID # resume specific # Model claude --model opus -p "hard task" claude --effort max -p "deep think" # Permissions claude --permission-mode auto # mostly auto claude --allowedTools Read,Write # restrict tools # Output claude -p --output-format json "q" claude -p --max-turns 5 "q" # CI claude -p "q" --output-format json --max-turns 3 --permission-mode bypassPermissions