Using the Claude CLI in scripts: claude -p, JSON output and safe defaults
By Tomás Herrera, NBT Most people meet the Claude CLI as an interactive chat in the terminal. The more interesting half is claude -p, which runs one task without the chat and exits. That turns Claude Code into something
By Tomás Herrera, NBT
Most people meet the Claude CLI as an interactive chat in the terminal. The more interesting half is claude -p, which runs one task without the chat and exits. That turns Claude Code into something you can put in a shell script, a package.json script, a git hook or a scheduled job.
This post covers the parts that matter once a script, not a person, is on the other end: exit codes, JSON and schema-checked output, permissions with nobody there to click "yes", and safe defaults for repositories you didn't write. Everything comes from the official headless and CLI reference docs at code.claude.com, checked on 6 December 2026.
The basics
claude -p "What does the auth module do?"
- Exit code
0on success, non-zero when the run fails, soset -eandifwork as you'd expect. - stdin is read, so you can pipe data in and redirect the answer out.
- Piped input is capped at 10 MB. For bigger inputs, write a file and name its path in the prompt.
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > explanation.txt
Pattern 1: a project-specific linter in package.json
Piping the diff in means Claude doesn't need permission to run git itself:
{
"scripts": {
"lint:claude": "git diff main | claude -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\""
}
}
npm run lint:claude now works like any other check. The escaped double quotes keep it portable to Windows.
Pattern 2: JSON you can parse
Add --output-format json and the answer comes wrapped in metadata, with the text in .result:
claude -p "Summarize this project in two sentences" --output-format json | jq -r '.result'
The JSON also includes total_cost_usd and a per-model cost breakdown, which is handy for logging what each scripted job costs.
The other formats are text (the default) and stream-json (newline-delimited events as they happen), which you'd use for long runs where you want progress.
Pattern 3: output that matches a schema
When a script needs fields rather than prose, pass a JSON Schema with --json-schema. The validated result appears in .structured_output:
claude -p "List the exported functions in src/auth.ts" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
| jq '.structured_output.functions'
Two details from the docs:
- An invalid schema fails immediately with
Error: --json-schema is not a valid JSON Schema. - If the run ends without valid structured output (for example, Claude declined), the
structured_outputfield is missing. Check for it before using it:
out=$(claude -p "..." --output-format json --json-schema "$SCHEMA")
echo "$out" | jq -e '.structured_output' >/dev/null || { echo "no structured output"; exit 1; }
Pattern 4: permissions when nobody is watching
In an interactive session you approve actions as they come up. In -p mode there's nobody to ask, so a call that needs approval is denied unless something approves it ahead of time. You have three tools.
Pre-approve specific tools with permission-rule syntax:
claude -p "Look at my staged changes and create an appropriate commit" \
--allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"
The space before * matters: Bash(git diff *) matches git diff with or without arguments, while Bash(git diff*) would also match git diff-index.
Pick a permission mode as the baseline:
| Mode | Use it for |
|---|---|
--permission-mode acceptEdits |
Edits and common file commands run without asking, for example "apply the lint fixes" |
--permission-mode dontAsk |
Anything that would prompt is denied; reads and allowed rules still work. Good for locked-down CI |
--permission-mode auto |
A classifier reviews actions instead of you |
Tell it nobody will answer:
claude -p "Update the dependency pins and run the tests" \
--permission-mode auto --permission-prompts none
With --permission-prompts none, anything that would wait on a person is denied, Claude is told not to retry, and the run continues. Tools that need a human, such as asking the user a question, are removed for that run.
Pattern 5: keep runs bounded
Two print-mode flags stop a script from running away:
claude -p "Fix the failing test in tests/api" \
--allowedTools "Bash(npm test *),Read,Edit" \
--max-turns 10 \
--max-budget-usd 1.50
--max-turns caps agent turns, and --max-budget-usd stops the run once the estimated API spend reaches the cap.
Safe defaults: use --bare for anything you didn't write
This one is easy to miss. Without --bare, claude -p runs the hooks in a project's .claude/settings.json and connects the MCP servers in its .mcp.json, even in a folder you've never trusted. No trust dialog appears in print mode.
--bare skips auto-discovery of hooks, skills, custom commands, subagents, MCP servers, auto memory and CLAUDE.md. It starts faster too. The docs call it the recommended mode for scripted calls and say it will become the default for -p in a future release.
claude --bare -p "Summarize README.md" --allowedTools "Read"
Things that change in bare mode:
-
Authentication: it never reads your subscription login or the keychain. Set
ANTHROPIC_API_KEY(a key from the Claude Console) or supply anapiKeyHelperthrough--settings. -
Context you want, you pass explicitly:
--append-system-prompt-filefor instructions,--settingsfor settings,--mcp-configfor MCP servers,--agentsfor subagents. - Settings files and their permission rules are still read.
If you need the project's configuration but not its hooks, the docs also suggest --setting-sources user (ignore project settings files) or --settings '{"disableAllHooks": true}' for that run.
Pattern 6: continuing a scripted conversation
claude -p "Review src/payments for error-handling gaps" > review.md
claude -c -p "Now write tests for the two most serious gaps"
-c continues the most recent conversation in the current folder. For anything long-lived, capture the session ID from the JSON output and pass it to --resume instead, so a different run in the same folder can't get in between.
A template for a scheduled job
#!/usr/bin/env bash
set -euo pipefail
cd /srv/myapp
claude --bare -p "Check package.json for outdated dependencies with known security advisories and list them" \
--allowedTools "Read,Bash(npm outdated *),Bash(npm audit *)" \
--permission-mode dontAsk \
--max-turns 8 \
--output-format json \
| tee -a /var/log/claude-deps.jsonl \
| jq -r '.result'
It's bounded, read-mostly, logs cost per run and has no hooks from the repository.
Command summary
| Need | Flag |
|---|---|
| One-shot run | -p |
| Machine-readable output |
--output-format json / stream-json
|
| Validated fields | --json-schema '<schema>' |
| Pre-approved tools | --allowedTools "..." |
| Baseline permissions |
--permission-mode acceptEdits / dontAsk / auto
|
| Nobody to answer | --permission-prompts none |
| Bounds |
--max-turns, --max-budget-usd
|
| Untrusted repo | --bare |
| Continue |
-c or --resume <id>
|
New to the tool itself? Our plain introduction to what is Claude Code covers the interactive side and a first session.
Disclosure: we make Ninja Builder, a desktop app that runs Claude Code in a window. For scripts and scheduled jobs, though, the Claude CLI on its own, as described here, is the right tool.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.