Sign in with Google
OpenToolslogo
ToolsExpertsSubmit a Tool
Advertise
HomeResourcesClaude CodeClaude Code CLI Reference: Every Command and Flag
PrevAllNext

Claude Code Resources

  • Claude Code Quick Start Guide: Install, Authenticate, Runquickstart
  • How to Write CLAUDE.md: Claude Code's Most Important File
  • Claude Code CLI Reference: Every Command and Flagreference
  • Claude Code in Your IDE: VS Code, JetBrains, and Desktop App
  • Claude Code Skills and Custom Commands: Extend Claude's Capabilities
  • Claude Code Hooks: Automate Your Workflow with Lifecycle Events
  • Claude Code MCP: Connect External Tools and Data Sources
  • Claude Code vs Cursor vs GitHub Copilot: 2026 Comparisoncomparison
  • Claude Code Subagents: Parallel Processing for Complex Tasks
  • Claude Agent SDK: Build Custom AI Agents Programmatically
  • Claude Code in CI/CD: GitHub Actions, GitLab CI, and Automation
  • 25 Advanced Claude Code Tips: From Power User to Protips
  • Everything Claude Code (ECC) - Configuration Framework & Toolkittoolkit

Claude Code CLI Reference: Every Command and Flag

referencebeginner8 min readVerified Apr 28, 2026

Complete reference for Claude Code CLI commands, flags, environment variables, and scripting patterns for automation and CI/CD.

claude-codeclireferencecommandsflags

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: use default for interactive work, acceptEdits or auto for semi-automated runs, and bypassPermissions only 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#

CommandDescription
claudeStart 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 -cContinue the most recent conversation
claude -rResume a previous session (select from list)
claude updateUpdate Claude Code to the latest version
claude installInstall or reinstall Claude Code
claude auth loginAuthenticate with your Anthropic account
claude auth logoutClear stored authentication credentials
claude auth statusShow current authentication state
claude agentsManage and list Claude Code agents
claude mcpManage MCP (Model Context Protocol) server connections
claude pluginManage Claude Code plugins
claude remote-controlControl a running Claude Code instance remotely
claude setup-tokenConfigure API token for programmatic access

Session & Interaction Flags#

FlagDescription
-p, --printPrint mode: output result and exit (non-interactive)
-c, --continueContinue the most recent conversation in the current directory
-r, --resumeResume a previous session; prompts you to select one
-n, --nameAssign a name to the session for easier retrieval
--session-idSpecify an exact session ID to resume
--fork-sessionFork an existing session into a new branch
--from-prLoad context from a pull request URL
--initInitialize the project with a CLAUDE.md file
--init-onlyOnly create CLAUDE.md, then exit
--maintenanceRun in maintenance mode (reduced features)
-v, --versionPrint the CLI version
--verboseEnable verbose logging output

Model & Effort Flags#

FlagValuesDescription
--modelsonnet, opus, or full name (e.g. claude-sonnet-4-6)Select the model to use
--effortlow, medium, high, xhigh, maxControl reasoning effort and token budget
--fallback-modelSame as --modelSpecify 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#

FlagDescription
--permission-mode defaultStandard mode: prompts for risky actions
--permission-mode acceptEditsAuto-accept file edits; still prompts for destructive actions
--permission-mode planRead-only: plan changes without executing them
--permission-mode autoAuto-accept most tool calls with minimal prompting
--permission-mode dontAskAttempt all actions; fail if permission is denied
--permission-mode bypassPermissionsSkip all permission checks (dangerous — sandbox only)
--dangerously-skip-permissionsAlias/shorthand for bypassPermissions
--allowedToolsComma-separated allowlist of tools the model may use
--disallowedToolsComma-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#

FlagDescription
--output-format textPlain text output (default)
--output-format jsonStructured JSON output
--output-format stream-jsonStreaming 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" }
FieldDescription
typeAlways "result" for completed runs
subtype"success" or "error"
total_cost_usdTotal API cost in USD
duration_msWall-clock duration in milliseconds
num_turnsNumber of conversation turns
resultThe final text response
session_idSession identifier for follow-up with --session-id

Turn and Bare Control#

FlagDescription
--max-turns NLimit the conversation to N turns; exit after the limit
--bareStrip 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#

VariableDescription
ANTHROPIC_API_KEYAPI key for direct Anthropic API access
CLAUDE_CODE_USE_BEDROCKSet to 1 to route requests through AWS Bedrock
CLAUDE_CODE_USE_VERTEXSet to 1 to route requests through Google Vertex AI
CLAUDE_CODE_USE_FOUNDRYSet to 1 to route requests through Anthropic Foundry
DISABLE_AUTOUPDATERSet to 1 to disable automatic CLI updates
DISABLE_UPDATESSet to 1 to disable all update checks
CLAUDE_CODE_SUBPROCESS_ENV_SCRUBScrub 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
PreviousHow to Write CLAUDE.md: Claude Code's Most Important FileNextClaude Code in Your IDE: VS Code, JetBrains, and Desktop App

On this page

  • Key Takeaways
  • Core Commands
  • Session & Interaction Flags
  • Model & Effort Flags
  • Permission Flags
  • Non-Interactive Mode (-p) Deep Dive
  • Basic One-Shot Query
  • Piped Input
  • Output Formats
  • JSON Output Structure
  • Turn and Bare Control
  • Key Environment Variables
  • Scripting Patterns
  • Piping Files for Analysis
  • CI Integration with Structured Output
  • Scheduled / Cron Tasks
  • Multi-Step Workflows with Session IDs
  • Error Handling
  • Quick Reference Cheat Sheet

Footer

Company name

The right AI tool is out there. We'll help you find it.

LinkedInX

Knowledge Hub

  • News
  • Resources
  • Newsletter
  • Blog
  • AI Tool Reviews

Industry Hub

  • AI Companies
  • AI Tools
  • AI Models
  • MCP Servers
  • AI Tool Categories
  • Top AI Use Cases

For Builders

  • Submit a Tool
  • Experts & Agencies
  • Advertise
  • Compare Tools
  • Favourites

Legal

  • Privacy Policy
  • Terms of Service

© 2026 OpenTools - All rights reserved.