Most of the time you talk to Claude in a back-and-forth session. But when you want it inside a script, you need it to run once, do the job, and exit. That is what headless mode is for.
Print and exit
The -p flag runs a single prompt and prints the result without opening an interactive session.
claude -p "Summarize the changes in the last commit in one sentence."
This returns text to standard output, which means you can capture it in a variable, pipe it onward, or write it to a file like any other command.
Pipe input in
Headless mode reads from a pipe, so you can feed it the output of another command.
git diff --staged | claude -p "Write a one-line summary of this diff."
cat error.log | claude -p "What is the most likely cause of these errors?"
Structured output for scripts
When a script needs to parse the result, plain text is fragile. Ask for JSON instead with --output-format json, which wraps the response in a predictable structure your code can read.
claude -p "List the files touched in the last commit." --output-format json
Mind the permissions
A headless run still respects your permission rules. For automation you control end to end, you can pick a permission mode with --permission-mode, and add trusted directories with --add-dir. Grant only what the task needs rather than reaching for the widest setting.
Headless claude -p is the building block for everything scripted: a pre-commit helper, a nightly report, a step in a larger shell pipeline. The next articles in this series lean on it, so get comfortable calling it and reading what it returns.
Comments
Be the first to comment.