Claude Code command line: sessions, flags and one-shot pipes
PLThe Claude Code command line is the claude binary’s launch flags and in-session controls: -c and -r resume earlier sessions, -n names them, --model, --effort, and --permission-mode set how a session runs, and -p runs one prompt and exits, so pipes and Git hooks can use it. All flags were checked on Claude Code 2.1.283; those that name a later version, on 2.1.296 (2026-10-12).
This page is for developers who already run Claude Code daily. You are 40 turns into a session, the answers are drifting, and you cannot remember which of yesterday’s sessions held the schema work. Meanwhile a teammate’s “quick” claude "..." in a Git hook hangs the commit forever. Each of those has an exact command-line answer.
What you get from the Claude Code command line
Section titled “What you get from the Claude Code command line”- A launch recipe that sets model, effort, permission mode, and extra directories per session instead of per habit.
- A session model that finds yesterday’s work by name, forks it safely, and never relies on a numeric index.
- A context routine for
/clear,/compact,/context, andEsc Escthat keeps long sessions sharp. - One-shot
claude -ppipes that return JSON your script checks, with tools switched off when the job is text in, text out. - Three copy-paste prompts: a commit-message generator, a pre-commit guard, and a handoff note that survives
/clear.
How do you launch Claude Code with the right settings?
Section titled “How do you launch Claude Code with the right settings?”Choose the settings when you start the session. Changing course 30 turns in costs more than a flag at launch.
# Terminal: a named session with a second repo in scopeclaude -n "billing-webhooks" --add-dir ../billing-sdk
# Start in plan mode for work you want designed before any editclaude --permission-mode plan "Plan the migration of webhook retries to a queue"
# Raise effort for a hard task instead of switching modelclaude --effort high
# Name a model explicitly: an alias (opus, sonnet, fable) or a full IDclaude --model opus| Flag | What it controls | When to reach for it |
|---|---|---|
-n, --name | Display name in the prompt box, the /resume picker and the terminal title | Every session you might come back to |
--add-dir | Extra directories the tools may access | A change spans two repositories or a shared package |
--permission-mode | manual, acceptEdits, plan, auto, dontAsk or bypassPermissions | plan for design work; the starting mode is fine for most sessions |
--effort | low, medium, high, xhigh or max | Hard reasoning or long refactors; tune this before changing model |
--model | Alias or full model ID for this session | Only when your own results say the default is wrong for the task |
-w, --worktree | Creates a Git worktree for the session | Parallel work that must not touch your current checkout |
The default model is the right start. From v2.1.280 that is Claude Opus 5.5 on every paid plan, on both release channels (checked 2026-10-12). The models hub keeps the current lineup and prices. Tune --effort before you switch model, and switch only when your evals say so.
From 2.1.283 (both release channels on 2026-10-12), interactive terminal sessions start in auto mode on supported models, where a classifier reviews each action; claude -p still starts in Manual (auto mode on third-party providers or with telemetry off, from v2.1.285). Shift+Tab cycles the permission modes inside a session. Configuration covers setting a default in settings.json instead of passing flags.
How do you resume the right Claude Code session?
Section titled “How do you resume the right Claude Code session?”-r takes a session ID or a search term, not a position in a list. There is no claude -r 5 (checked on 2.1.283).
# Most recent conversation in this directory, no pickerclaude -c# Interactive picker of past sessionsclaude -r# Picker pre-filtered by a search term, such as the session nameclaude -r billing# Direct resume; the ID comes from the picker or from `-p --output-format json`claude -r 3f2c9a1e-5b7d-4c1a-9e0f-2d8b6a4c7e11# Branch an old session into a new ID and leave the original intactclaude -r --fork-sessionThree habits make resume reliable:
-
Name at launch.
claude -n "billing-webhooks"puts the name in the picker. Inside an unnamed session,/renamefixes it later. -
Use
-conly when the last session in this directory is the one you want. It picks by recency, not by topic. -
Fork before an experiment.
--fork-sessionwith-ror-ckeeps the original conversation as a fallback, so a wrong turn costs nothing.
Pull-request work has its own shortcut. claude --from-pr 412 resumes the session linked to that PR, and claude --from-pr without a value opens the picker.
How do you keep a Claude Code session running while you do something else?
Section titled “How do you keep a Claude Code session running while you do something else?”A long task does not need to hold your terminal. --bg starts the session in the background and prints a short ID that the management subcommands take:
# Terminal: start a background session in its own worktreeclaude --bg -w webhook-retries "Move webhook retries to the queue and make the billing tests pass"
claude agents # list background sessionsclaude logs ID # recent terminal output of one sessionclaude attach ID # open it in this terminalclaude stop ID # stop it; the conversation is kept for --resumeReplace ID with the short ID that --bg printed. The worktree keeps the background edits away from the checkout you are still working in. Background sessions and the agent view are covered in agent view. From v2.1.290 (latest channel only on 2026-10-12), claude attach and claude logs also accept part of a session’s name in place of the ID; put a name with spaces in quotes.
Two more commands take you out of the terminal session or clear it away. claude --desktop (v2.1.285) opens the Claude Desktop app on the current directory and exits without starting a terminal session; add --continue, or --resume with a session ID, to open that session in Desktop instead. claude purge [path] deletes the local state Claude Code keeps for a project: transcripts, task lists, debug logs, file-edit history, prompt-history lines, and the project’s entry in ~/.claude.json. --dry-run lists what it would delete, -y skips the confirmation, and --all covers every project. Before v2.1.288 (latest channel only on 2026-10-12) it was claude project purge, and the old name still works and prints a notice. Source: Claude Code CLI reference, checked 2026-10-12.
How do you keep a long session’s context sharp?
Section titled “How do you keep a long session’s context sharp?”Long sessions degrade because every turn carries the whole history. Four controls manage that, in order of how much they discard:
| Control | What it does | Use it when |
|---|---|---|
/context | Shows what fills the context window | Before you decide whether to compact or clear |
/compact | Summarises the history and keeps working | The task continues, but the early turns are noise |
Esc Esc with an empty prompt (or /rewind) | Restores code and conversation to an earlier checkpoint | The last few turns went the wrong way |
/clear | Starts an empty conversation in the same terminal | The task is done or the next task is unrelated |
/clear is the cheapest reset. It does not delete work that lives in files, so write the state you need into a file first; the handoff prompt below does exactly that. /rewind can even return to a point before a /clear.
Reference files with @ so Claude reads exactly what you mean instead of searching for it:
Make @src/billing/webhooks.ts retry with exponential backoff, following the pattern in @src/queue/retry.ts. Keep the public signature unchanged.Type @ and pick the path from the suggestions. /usage shows session cost and plan limits (/cost is an alias). The full command list lives in slash commands mastery.
How do you run Claude Code in a pipe or a Git hook?
Section titled “How do you run Claude Code in a pipe or a Git hook?”-p (--print) runs one prompt and exits. A bare claude "..." opens the interactive session and waits for input, so any script, hook or CI step needs -p.
# Terminal: a single file on stdin, text outclaude -p "Explain what this SQL does and flag any full-table scans" < reports/monthly.sql
# A diff on stdingit diff main...HEAD | claude -p "Summarise these changes for a release note"
# Pipe several files; you cannot redirect a directory (`< src/` fails)cat src/billing/*.ts | claude -p "List every function that swallows an exception"Scripts need an outcome they can branch on, not prose. Three flags give you that:
| Flag | Effect |
|---|---|
--output-format json | One result object; the answer is in .result, failure in .is_error, and cost in .total_cost_usd |
--json-schema '<schema>' | Validates the answer against your schema and returns it in .structured_output |
--tools "" | Disables every built-in tool, so a text-in, text-out job cannot run commands or edit files |
Two more flags bound a headless run: --max-budget-usd 0.50 caps its spend (print mode only), and --allowedTools "Bash(git diff *)" pre-approves just the commands the job needs. claude -p starts in Manual permission mode, not auto mode (except on third-party providers or with telemetry off, where it starts in auto mode from v2.1.285); add --permission-mode dontAsk, which denies anything that would prompt on every provider (file reads in the working directories and read-only Bash commands still run), and --permission-prompts none so that nothing waits for an answer. Headless scripting, cron, and cost caps are covered in depth in scripting Claude Code.
Copy-paste prompts for the Claude Code command line
Section titled “Copy-paste prompts for the Claude Code command line”How do you check command-line output without reading every line?
Section titled “How do you check command-line output without reading every line?”Speed from the command line only helps if the result is checked by something other than your eyes.
- Headless runs fail closed. The guard above blocks on
is_errorand on a schema-validated verdict, so a model error or a malformed answer stops the commit instead of passing it. - Behaviour is proven by your suite. End interactive tasks with the prompt “run the tests and the type check, and paste the last 20 lines of each”. Accept the change when the gates are green, not when the diff looks plausible.
- A second pass reviews the diff. Run
/code-reviewbefore you commit; review automation moves the same check into CI. - File edits are reversible.
Esc Escrestores Claude’s edits and the conversation, but not the side effects of shell commands (migrations, pushes, deletes), so keep those behind approval.--fork-sessionkeeps an untouched original.
You still own the merge. The gates tell you which diffs deserve a line-by-line read: the ones that fail them or touch security-sensitive paths.
When Claude Code command-line habits break
Section titled “When Claude Code command-line habits break”claude -ropens the wrong session. A search term matches more than one session, or-cpicked the most recent one in this directory. Recovery: name sessions with-nor/rename, and resume by the ID from the picker when it matters.- A hook or CI step hangs. The script calls
claude "..."without-p, which opens an interactive session. Recovery: add-p, and add--tools ""when the job only transforms text. jqreturnsnull.-pprints plain text unless you pass--output-format json; with--json-schema, the answer is in.structured_output, not.result. Recovery: set the format explicitly and read the field that matches it.- A headless run in an unknown directory behaves unexpectedly. Print mode skips the workspace trust dialog, and settings files that fail validation are silently ignored. Recovery: run
claude -ponly in directories you trust, and runclaude doctorwhen settings seem to be missing. - The session keeps asking for the same approval. The fix is an allow rule for that tool in
/permissionsorsettings.json, not--dangerously-skip-permissions. That flag bypasses every check; its own help text recommends it only for sandboxes with no internet access, and nowhere else is it safe. - A hook blocks every commit with
error_max_budget_usd. The cap stops a run once its spend passes the limit, so a run can finish above it, and a cap below the cost of one model call fails every time. Recovery: raise--max-budget-usdto a few times the.total_cost_usdof a normal run. - Customisations break startup. A bad hook, plugin, or
CLAUDE.mdmakes every session misbehave. Recovery:claude --safe-modestarts with customisations disabled so you can find the culprit.
Where to go next from the command line
Section titled “Where to go next from the command line”- Previous: features you haven’t tried.
- Next: large codebase management, where session and context control matter most.
- Every built-in command and shortcut: slash commands mastery.
- tmux, panes and shell integration: terminal mastery.
- Turning your prompts into reusable
/commands: custom commands. - The Codex equivalent: Codex CLI commands.