Skip to content

Claude Code CLI — advanced ​

Advanced Power-user flags for automation, permissions, and CI. Easy to misuse.

Verified against Claude Code 2.1.220 (claude --help) and official docs at code.claude.com/docs. Flags evolve — re-check with claude --help and the CLI reference on your install. Official note: --help does not list every flag.

Not a daily default

Do not make --dangerously-skip-permissions or bypassPermissions your everyday workflow. Prefer interactive approval, allowlists, acceptEdits / auto modes, and sandboxing first.

Safer alternatives first ​

GoalPreferAvoid as default
Fewer edit prompts while you watch--permission-mode acceptEdits or Shift+TabFull bypass
Long autonomous stretch with safety checks--permission-mode auto (classifier; account/model requirements)YOLO bypass on host
Locked-down CI / scripts--permission-mode dontAsk + permissions.allow / --allowedToolsOpen bypass on shared runner with secrets
Bash isolation (macOS / Linux / WSL2)/sandbox + settings (sandbox.enabled)Unsandboxed shell on host with secrets
One-shot analysisclaude -p "..." with narrow --allowedTools / --toolsBroad tool access
Faster, reproducible scripts--bare -p + explicit flags onlyLoading every user MCP/hook by accident

Interactive baseline remains the starter page.

Permission modes (the real control surface) ​

--permission-mode <mode> sets how often Claude pauses for approval. Shift+Tab cycles modes in an interactive session (not every mode is always in the cycle).

ModeConfig / CLI valueRuns without asking (roughly)Best for
Manualdefault (CLI alias: manual on recent builds)Reads onlySensitive work, getting started
Accept editsacceptEditsReads, file edits, common FS shell (mkdir, mv, cp, …) in scopeIterate while reviewing diffs later
PlanplanExplore / plan; edits blocked until you approve the planDesign before change
AutoautoMost tools, with classifier background checksLong tasks when available for your account/model
Don't askdontAskOnly pre-approved / allowlisted tools (else deny)CI with tight allowlists
BypassbypassPermissionsNearly everything (few circuit breakers remain)Isolated containers / VMs only
bash
claude --permission-mode plan
claude --permission-mode acceptEdits
claude --permission-mode dontAsk
claude --permission-mode auto

Persistent default (user or project settings — see official settings docs):

json
{
  "permissions": {
    "defaultMode": "acceptEdits"
  }
}

TIP

defaultMode: "auto" in project settings is ignored on recent versions so a repo cannot grant itself auto mode. Put auto defaults in user settings (~/.claude/settings.json) if you want them.

Auto mode in depth (the upgrade from bypass) ​

auto is what Anthropic recommends instead of --dangerously-skip-permissions. It eliminates routine prompts like the bypass flag does, but a separate classifier model reviews every action before it runs and blocks anything destructive, off-target, or that looks driven by hostile content the agent read (prompt-injection defense). Bypass has zero such checks.

bash
claude --permission-mode auto
  • Requires recent models (Opus 4.6+ / Sonnet 4.6+, or Fable 5) on the Anthropic API; on Bedrock / Vertex / Foundry it is available by default on current versions (the CLAUDE_CODE_ENABLE_AUTO_MODE opt-in requirement was removed)
  • Auto-pauses after 3 consecutive or 20 total classifier blocks and falls back to normal prompting
  • Tune what it trusts in settings: autoMode.environment, autoMode.allow / autoMode.soft_deny / autoMode.hard_deny, and autoMode.classifyAllShell to route every shell command (not just risky patterns) through the classifier — see auto mode config

What bypass does not skip ​

Even in bypassPermissions / --dangerously-skip-permissions:

  • Explicit ask rules and some org-mandated connector / MCP consent tools still prompt
  • Circuit breakers for destroying / or home (rm -rf /, rm -rf ~, and related forms on recent versions) still prompt
  • It is not a substitute for OS isolation, network policy, or secret hygiene

Protected paths (.git, shell rc files, .claude config, package manager configs, etc.) are not auto-approved in normal modes; bypass allows writes there. Details: permission modes.

Dangerous flags (use with intent) ​

--dangerously-skip-permissions ​

bash
claude --dangerously-skip-permissions
# equivalent:
claude --permission-mode bypassPermissions
DoesSkip permission prompts; tools run immediately (including protected-path writes)
When appropriateThrowaway container / VM / devcontainer with no host secrets, preferably no open internet; ephemeral CI job with tight scope and disposable workspace
NeverDaily laptop on real repos with production credentials; untrusted third-party code; shared machines as root
AlsoRefused as root/sudo on Linux/macOS outside a recognized sandbox

First interactive enable shows a responsibility dialog (once). Non-interactive (-p) shows no dialog. Background (--bg) sessions started this way may be refused until you accepted the dialog interactively.

--allow-dangerously-skip-permissions ​

bash
claude --permission-mode plan --allow-dangerously-skip-permissions

Adds bypassPermissions to the Shift+Tab cycle without starting in it. Safer than always-on bypass when you only need the option later.

Other dangerously-* names (research / edge) ​

Official CLI reference also documents flags such as --dangerously-load-development-channels (channels research preview — load non-allowlisted channel sources). Treat any dangerously-* flag as opt-in and re-read docs for your version.

There is no CLI flag literally named yolo. Closest behaviors:

IntentMechanism
Skip all permission UI--dangerously-skip-permissions / bypassPermissions
Fewer prompts, still gatedauto mode + classifier
Bash freer inside a boxSandbox auto-allow (/sandbox)
Sandbox escape hatch (per command)Model may retry with unsandboxed Bash when allowed by settings (allowUnsandboxedCommands) — still permission-gated unless you bypassed

Tool allow / deny (prefer over full bypass) ​

FlagRole
--allowedTools / --allowed-toolsAuto-approve matching tools (does not by itself remove all others from context)
--disallowedTools / --disallowed-toolsDeny / strip tools (bare name can remove tool; scoped Bash(rm *) denies matching calls)
--toolsRestrict available built-ins ("" = none, default = all, or e.g. Bash,Edit,Read)
--permission-prompt-tool <mcp_tool>Route permission prompts to an MCP tool in non-interactive (-p) mode instead of denying

Rule syntax uses permission patterns (space before * matters for Bash prefixes):

bash
# Pre-approve only what the task needs
claude -p "Run tests and fix failures" \
  --allowedTools "Bash,Read,Edit"

# Narrow git commit path
claude -p "Create a commit for staged changes" \
  --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

# Deny broad damage classes
claude --disallowedTools "Bash(rm *),Bash(git push *)"

CI-friendly locked mode:

bash
claude -p "Summarize failing tests" \
  --permission-mode dontAsk \
  --allowedTools "Read,Bash(npm test *),Bash(npm run test *)"

Anything not allowed (and not read-only built-in) is denied in dontAsk — the run will not hang waiting for a human.

Non-interactive / headless / print mode ​

FlagPurpose
-p / --printRun prompt, print result, exit (pipes, CI, scripts)
--output-format text|json|stream-jsonShape of stdout (with -p)
--input-format text|stream-jsonStdin protocol (with -p)
--json-schema '<schema>'Structured result under structured_output (with json format)
--include-partial-messagesToken streaming events (with stream-json)
--verboseNeeded for useful stream-json event streams
--no-session-persistenceDo not save session (with -p)
--max-turns <n>Cap agentic turns for this print run
--max-budget-usd <amount>Cap API spend for this print run
--fallback-model <models>Comma-separated fallback when primary unavailable (with -p)
bash
# One-shot
claude -p "What does the auth module do?"

# Pipe (stdin capped ~10MB as of recent versions — use a file path for larger logs)
cat error.log | claude -p "explain the root cause"

# Machine-readable + cost fields in JSON payload
claude -p "Summarize this project" --output-format json

# Structured extraction
claude -p "List main exported functions in src/api.ts" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'

Workspace trust in print mode

With -p (or non-TTY stdout), the workspace trust dialog is skipped. Only run in directories you trust. Invalid settings may be silently ignored in this mode.

Bare mode (scripts / CI) ​

bash
claude --bare -p "Summarize this file" --allowedTools "Read"

--bare skips auto-discovery of hooks, plugins, MCP, auto-memory, CLAUDE.md, keychain OAuth, etc. Auth for Anthropic is ANTHROPIC_API_KEY or apiKeyHelper via --settings. Pass context explicitly (--append-system-prompt, --mcp-config, --settings, --add-dir, …). Recommended for reproducible automation; may become default for -p later.

Continue / resume sessions ​

bash
claude -c                           # continue most recent in this directory
claude -c -p "now fix the types"    # continue non-interactively
claude -r "session-id-or-name" "finish the PR"
claude --resume abc123 --fork-session   # new session id, keep history fork

# Capture id for multi-step scripts
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"

Session lookup is scoped to the current project directory (and its worktrees).

Model, effort, cost ​

bash
claude --model sonnet
claude --model opus
claude --model claude-…   # full model id when you need a pin
claude --effort high      # low | medium | high | xhigh | max (and newer aliases per version)
claude -p "…" --max-budget-usd 2.50
claude -p "…" --fallback-model sonnet,haiku

In interactive sessions, /cost shows session usage. Print JSON includes cost metadata (total_cost_usd, etc.) for script accounting.

Model aliases and effort levels change with releases — confirm with claude --help and model config docs.

CI / automation patterns ​

Auth ​

MethodNotes
ANTHROPIC_API_KEYCommon for API billing / bare mode
claude setup-tokenLong-lived OAuth token for subscription CI; prints token (store as secret)
Cloud providersBedrock / Vertex / Foundry use their own credentials
Official Actionsanthropics/claude-code-action

Never commit tokens. Scope runner secrets to the job.

Prefer this shape for CI ​

bash
claude --bare -p "$PROMPT" \
  --permission-mode dontAsk \
  --allowedTools "Read,Edit,Bash(npm test *)" \
  --max-budget-usd 5 \
  --output-format json

Safer progression:

  1. Read-only analysis with --tools / allowlist Read+Grep only
  2. acceptEdits or narrow Edit+Bash allowlists on a disposable branch / worktree
  3. dontAsk + allowlist for unattended jobs
  4. bypassPermissions only in network-isolated disposable environments

GitHub / GitLab ​

Use Anthropic’s GitHub Actions / GitLab CI guides. Cap turns/budget via action claude_args when supported; set job timeouts and concurrency so runaway agents do not burn the budget.

yaml
# Sketch only — verify inputs against current action docs
- uses: anthropics/claude-code-action@v1
  with:
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    claude_args: "--max-budget-usd 3"

Sandbox (Bash isolation — not the same as permission mode) ​

/sandbox configures OS-level limits on Bash (filesystem + network). It is orthogonal to permission modes:

  • Permission mode: may this tool run?
  • Sandbox: what can the shell touch once it runs?
PlatformSupport
macOSSeatbelt (built-in)
Linux / WSL2bubblewrap + socat (install packages)
Native WindowsNot supported — use WSL2
text
# inside interactive claude
/sandbox

Settings sketch (see sandboxing docs):

json
{
  "sandbox": {
    "enabled": true,
    "failIfUnavailable": true,
    "allowUnsandboxedCommands": false,
    "network": {
      "allowedDomains": ["registry.npmjs.org", "github.com"],
      "strictAllowlist": true,
      "deniedDomains": []
    },
    "credentials": {
      "files": [
        { "path": "~/.ssh", "mode": "deny" },
        { "path": "~/.aws/credentials", "mode": "deny" }
      ],
      "envVars": [
        { "name": "NPM_TOKEN", "mode": "deny" }
      ]
    }
  }
}

Sandbox is not a full VM. Broad allowedDomains, disabled filesystem isolation (sandbox.filesystem.disabled: true keeps network egress control but skips FS isolation), or docker.sock-style exceptions weaken it. Prefer combining sandbox plus least-privilege permission mode for unattended work.

Session / workspace power flags ​

FlagPurpose
--add-dir <dirs…>Extra directories Claude may read/edit
-w / --worktree [name]New git worktree for the session
--tmuxtmux (or iTerm panes) with worktree
--bg / --backgroundBackground agent; manage via claude agents (not with -p)
--agent / --agentsPick or define subagents
--system-prompt / --append-system-promptReplace or extend system prompt
--settings <file-or-json>Inject settings for the run
--mcp-config / --strict-mcp-configMCP servers for the session
--safe-modeDisable customizations (hooks, plugins, project CLAUDE.md discovery, …) for troubleshooting
--session-id <uuid>Force session UUID
-n / --nameDisplay name for resume UI
--from-pr [n|url]Resume session linked to a PR
--remote-controlRemote Control host session — see Remote Control
--chrome / --no-chromeChrome integration
bash
claude -w feat-login --permission-mode plan
claude --add-dir ../shared-lib --permission-mode acceptEdits
claude --safe-mode   # broken config investigation

Background agents ​

bash
claude --bg "investigate the flaky test"       # returns immediately; runs detached
claude agents                                  # list / manage background sessions
claude agents --dangerously-skip-permissions   # scope bypass to dispatched background sessions only
claude daemon status                           # daemon supervising background sessions

Scoping bypass to claude agents keeps your interactive default safe while unattended runs skip prompts — still combine with worktrees, budget caps, and sandbox settings.

Advanced flag cheat sheet ​

Flags marked ⚠ need isolation or tight allowlists — not default daily use.

FlagRiskSummary
-p / --printMedNon-interactive; skips trust dialog
--bareLowMinimal discovery; good for CI
--permission-mode default|manualLowManual approvals
--permission-mode acceptEditsMedAuto file edits in scope
--permission-mode planLowPlan without editing (until approve)
--permission-mode autoMedClassifier-based autonomy
--permission-mode dontAskMedDeny unless pre-approved — good for CI
--permission-mode bypassPermissions⚠ HighSkip checks
--dangerously-skip-permissions⚠ HighSame as bypass
--allow-dangerously-skip-permissions⚠ MedEnable bypass in mode cycle only
--allowedTools / --disallowedToolsMedAllow / deny rules
--toolsLow–MedRestrict tool inventory
--model / --effort / --fallback-modelLowModel selection
--max-budget-usdLowSpend cap (-p)
-c / --continue / -r / --resumeLowSession continuity
--fork-sessionLowFork on resume
--output-format / --json-schemaLowMachine output
--system-prompt* / --append-system-prompt*MedPrompt control
--add-dirMedExtra filesystem scope
--worktree / --tmuxLowIsolated git workspace
--bgMedBackground agents
--safe-modeLowStrip custom config
--verbose / --debug / --debug-fileLowDiagnostics
Sandbox settings / /sandboxLow–MedBash FS/network isolation

If a flag is uncertain on your build: claude --help and CLI reference.

Safety checklist ​

Appropriate

  • CI job on a disposable runner, allowlisted tools, budget cap, no long-lived prod credentials in the environment
  • Ephemeral container without host mounts of ~/.ssh, cloud creds, or production kubeconfigs
  • Local experiment on a throwaway clone / worktree you can delete

Never / almost never

  • Host machine with production secrets + bypass permissions + network
  • Untrusted repository (supply-chain / prompt injection) with broad tool access
  • Root/sudo + skip-permissions on a real workstation
  • Copy-pasting “YOLO” aliases into your global shell profile as the default claude command

Before any high-autonomy run

  1. Clean git state or dedicated branch / worktree
  2. Narrow tools and permission mode
  3. Budget / timeout caps
  4. Prefer sandbox or container isolation
  5. Review diffs before push

Official docs ​

Starter overview: Claude Code CLI.