CLI & Headless Mode
Most of this book assumes you’re sitting in front of Claude Code, watching it work and answering its prompts. This chapter is about the other half of its life: Claude Code as a command-line program you invoke from a script, a CI job, a git hook, or a shell pipeline, with no human in the loop. That mode is called headless — claude -p "..." runs a single non-interactive turn, prints the result, and exits — and it’s where Claude Code stops being a chat tool and becomes infrastructure.
The shift is bigger than a flag. Interactively, you are the loop: you catch mistakes, answer permission prompts, redirect when the approach is wrong. Headless, there is no you — the run has to be self-contained, bounded, and safe to leave alone. That changes what good usage looks like. Output has to be machine-readable when a program consumes it. Autonomy has to be fenced with budgets and turn limits, because a runaway loop with nobody watching burns time and money. State has to be carried explicitly across invocations rather than living in a conversation. The interactive affordances you lean on are gone, and their replacements are flags and exit codes.
This chapter starts with when to go headless at all, then treats claude -p as a Unix utility you pipe data through and compose into pipelines. It covers structured output for programs that read results, the guardrails every unattended run needs, and chaining turns with session IDs. It looks at shaping the system prompt for scripted runs, and closes with the step beyond the CLI — the Agent SDK — for when your automation grows from a script into a product.