Vibe coding with Claude Code course Β· Module 15: Advanced Claude Code
Claude Code without a conversation: the -p mode, pipes and sessions
In this lesson13
Thirteen clones behind you and you have probably noticed that some of your orders are given daily in the same words. Before a commit you ask for a review of the changes, after a break for a summary of the diff, and when CI fails you paste the log and ask for the cause. Every time you open a session, retype the same request and wait. In this last module you take Claude Code where nobody watches it: into scripts, loops and CI.
What you already know
In lesson 12_5 you ran claude -p with the flags --allowedTools, --permission-mode dontAsk, --max-turns and --output-format json, and in lesson 12_7 you put Claude into GitHub Actions. From lesson 4_10 you know claude -c, claude -r and named sessions, and from lesson 2_9 the /code-review command and reading a diff in Cursor. In lesson 1_5 you met git add, and in lesson 5_10 you heard that Sonnet costs less for routine work. I will not repeat that here: I am adding what an order given without a conversation needs.
What you will learn
- feeding Claude data through a pipe and saving the answer to a file;
- choosing the right diff and not sending an empty one;
- forcing the shape of the answer with a sentence or a JSON schema;
- narrowing the tools, the model and the login of a run;
- returning to
-pruns like ordinary sessions.
Three terminal characters: |, < and >
A stream is text that a program takes as input or prints as output. The vertical bar |, called a pipe, connects the output of one command to the input of the next, and claude -p reads such input together with your request:
git diff --cached | claude -p "Summarise these changes in three bullet points."Claude gets the diff served on a plate, so it does not have to search the project for anything. No file changes, and the command ends together with the answer. The other two characters redirect a stream: < pours a file into the input, and > writes the output to a file.
claude -p "Explain the cause of the first error in this log." < build.log > explanation.mdMind one thing: > empties the target file before the command even starts, so never point the output at a file that Claude is supposed to read. Piped input has a limit of 10 MB (as of November 2026); for a larger file, name its path in the request instead.
Which diff: three portions of changes
Git keeps changes in three places, and each command shows a different portion:
git diff # changes not yet added with git add
git diff --cached # the staging area: what will go into the commit
git diff main...HEAD # commits of the branch since it split from mainThree dots mean "count from the fork", so you will not see other people's commits that landed on main in the meantime. None of these commands writes anything. The trap waits in the empty diff: after git add, a plain git diff prints nothing, Claude receives only the request and, with full confidence, tells you about nothing. So before a commit you review --cached, and before a pull request main...HEAD.
Request for Claude Code
In Treasure Map you asked Claude for two changes in lib/pinInput.ts: a pin may have an image from a full address, and there may be ten tags. You ran git add lib/pinInput.ts, and before you sign the commit you want a list of problems, not a lecture.
Request for Claude Code (in the Cursor terminal):
git diff --cached | claude -p "Review these changes before the commit: bugs and security.
Answer with a list only, one line per problem:
file:line | problem | suggestion.
No introduction and no summary. If you find nothing, write: No issues found." \
--model sonnet --tools ""The shape of the answer is in the request, and two flags turn the review into a quick reflex. --model sonnet picks the cheaper model for routine work, and --tools "" takes all tools away from Claude, so it sees only the diff and answers in a single turn.
What Claude wrote
Nothing appeared on disk, a list stands in the terminal. Here is an abridged version of our run:
lib/pinInput.ts:9 | z.url() accepts any scheme (javascript:, data:, http:) and any host | narrow it to https: and the hosts from images.remotePatterns
lib/pinInput.ts:9 | startsWith("/pins/") lets /pins/../../something through | reject paths containing ..
lib/pinInput.ts:9 | the shared union message replaced the exact messages | separate messages for each branch
lib/pinInput.ts:13 | the limit is 10, but the message says "At most 5 tags." | make the limit and the message match
lib/pinInput.ts:13 | the limit was doubled without a reason | confirm the change and add a testEvery line has a file, a line number and a suggestion, so it can be checked, and a script could even count them. Claude fixed nothing: a review from a pipe gives an opinion, not a change.
Captain's review
Open the Source Control panel in Cursor, expand Staged Changes and click lib/pinInput.ts. Compare each item with the diff:
- Is the line in the diff? Lines 9 and 13 are. A number outside the diff means a remark about old code or an invention, so check it in the file.
- Does the charge hold up? The first one does:
z.url()from Zod letjavascript:alert(1)through in our project. The second concerns a line whose meaning did not change; that is a separate task, not this commit. The fifth is a guess without evidence, so you reject it. - What did the reviewer not see? The test "rejects an image outside /pins/" in
lib/pinInput.test.tsfails after this change, asnpm run test -- --runwill show. Without tools Claude did not look at the tests: a quick review from a pipe replaces neither the tests nor/code-review.
A typical agent mistake is an essay instead of a list when the request does not give the shape of the answer: paragraphs, headings and praise that you cannot compare with the diff. You recognise it by a first sentence like "Here is my analysis", and one line with a template of the answer cures it.
Writing without consent: what -p does
What happens when you ask for a file write in -p mode and add no permission flag? The documentation says that claude -p today starts in Manual mode and rejects every call that needs consent. We checked it on Treasure Map:
claude -p "Write Vitest tests for @lib/plural.ts and save them in lib/plural.test.ts." \
--model sonnet --tools "Read,Write" --max-turns 3 --output-format jsonThe file was not created. In the JSON, the permission_denials field listed the rejected Write tool along with the whole content of the tests, and in result Claude wrote that permissions had blocked the write. Most important: the command ended with exit code 0, that is, success. A script that looks only at the exit code will decide everything went well, so check the file or permission_denials. You approve a write with a flag (--allowedTools "Write" or --permission-mode acceptEdits), or you ask for the content alone and send it to a file with >, which you will see in the next lesson.
Three tool flags
These three flags sound alike and do different things:
claude -p "..." --tools "Read" # the toolset: only Read
claude -p "..." --allowedTools "Bash(npm run test *)" # tests without asking, the rest as usual
claude -p "..." --disallowedTools "Bash(git push *)" # this command will never run--tools narrows the set of built-in tools, and "" takes all of them away. --allowedTools takes nothing away, it only approves the listed calls in advance. --disallowedTools with a bare tool name removes that tool from Claude's reach, and with a pattern it rejects only the matching commands. I recommend thinking of it this way: first --tools says which tools Claude may reach for at all, then --allowedTools says what it does from that set without asking.
A shape forced by a schema
Models usually respect the sentence "answer with a list", but a script prefers a guarantee. The --json-schema flag takes a JSON schema, that is, a description of the fields the result must have. Save it in scripts/review-schema.json:
{
"type": "object",
"properties": {
"findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file": { "type": "string" },
"line": { "type": "integer" },
"problem": { "type": "string" },
"fix": { "type": "string" }
},
"required": ["file", "line", "problem", "fix"]
}
}
},
"required": ["findings"]
}The schema says: an object with a findings array, and in it every problem with a file, a line number, a description and a fix. This file runs nothing, it only describes a shape. Now a run that uses it:
git diff --cached | claude -p "Review these changes before the commit: bugs and security." \
--model sonnet --tools "" --output-format json \
--json-schema "$(cat scripts/review-schema.json)" | jq -c '.structured_output.findings[]'An answer that follows the schema lands in the structured_output field, and jq -c prints each problem as one line of JSON. Ours produced four problems with the same lines 9 and 13. The documentation warns that when a run ends without a valid result, there is no structured_output field, so check for it before a script trusts the count.
Model, login and --bare
Without --model, a script takes the default model from your settings, that is, your last choice from /model. Our first review run went without this flag and without --tools "": the most expensive model from the settings read files, used up --max-turns 3, ended with an error and no answer, and by estimate cost more than five times as much as a run with --model sonnet.
The login also works differently in a script. When ANTHROPIC_API_KEY is set in the environment, -p mode always uses the key, so you pay for tokens despite the subscription. claude auth status --text shows what you are logged in with. For CI on a subscription, claude setup-token prints a long-lived token that you put into the CLAUDE_CODE_OAUTH_TOKEN secret, as in lesson 12_7.
The --bare flag skips hooks, skills, subagents, plugins, MCP servers, automatic memory and CLAUDE.md, so a run does the same thing on every machine. But it does not read your login or CLAUDE_CODE_OAUTH_TOKEN: it needs ANTHROPIC_API_KEY or apiKeyHelper, that is, paying for tokens. It is a flag for CI with an API key, not for a laptop on a subscription. The other side of the coin: without --bare, a -p run in someone else's repository will run the hooks from its .claude/settings.json and connect the servers from .mcp.json without asking anything. Read the .claude/ folder of a stranger's project before you run a script on it.
Sessions you come back to
A -p run is a session too. claude -p "..." --continue appends the next request to the last conversation in the folder, say "now propose a fix for line 13". But a plain claude -c skips sessions from -p, so you return to a particular run by its identifier:
ID=$(git diff --cached | claude -p "Review these changes." --model sonnet --output-format json | jq -r '.session_id')
claude -p "Propose a fix for line 13." --resume "$ID"The first line saves the session identifier from the session_id field, the second appends a new request to the same conversation, with the whole review in its history, even from another folder. When you want to show Claude a second project, for example the tests from the Spotify clone, add --add-dir ../sea-shanty-sounds at the end of the command, after the request: the flag accepts several directories and treats everything after it as paths.
Next step
Close the review inside a script so you do not retype it every day. In a Claude Code session write:
Save the review from the pipe as scripts/code-review.sh. When the staging area is empty,
the script must print a hint and finish without calling Claude.
Done when: the script has that check and the same claude -p command as above.
Do not run it, I will do that myself in the terminal.In Cursor open scripts/code-review.sh and read what appeared:
#!/bin/bash
# code-review.sh: review the staged changes before you commit
if git diff --cached --quiet; then
echo "The staging area is empty. First: git add <files>"
exit 1
fi
git diff --cached | claude -p "Review these changes before the commit: bugs and security.
Answer with a list only, one line per problem:
file:line | problem | suggestion.
No introduction and no summary. If you find nothing, write: No issues found." \
--model sonnet --tools "" --max-turns 2git diff --cached --quiet prints nothing, it only ends with success when the staging area is empty, so if stops the script before you pay for a review of nothing. --max-turns 2 is a brake in case a run drags on. Then ask Claude for fixes from the list, run npm run test -- --run and bash scripts/code-review.sh, and sign the commit when the reviewer answers "No issues found" or the remarks that are left you have consciously rejected.
In the editor next door you will assemble a command from the pipe and the flags, and the simulator will show what reaches Claude, what it is allowed to do and who pays for the run.
Remember: the conversation happens on the bridge, and -p is the watch that works while you sleep, provided you left it a clear order.
Code for this lesson: App.tsx
// Watch simulator: what reaches Claude in -p mode, what it may do and who pays
import { useState } from 'react';
type Source = 'cached' | 'worktree' | 'branch';
type Task = 'review' | 'write';
type Tools = 'default' | 'read' | 'none';
type Mode = 'manual' | 'acceptEdits' | 'dontAsk';
type Auth = 'subscription' | 'apiKey' | 'oauthToken';
type Output = 'text' | 'json' | 'schema';
export interface Config {
task: Task;
source: Source;
staged: boolean;
tools: Tools;
mode: Mode;
allowWrite: boolean;
sonnet: boolean;
bare: boolean;
auth: Auth;
output: Output;
}
export interface Verdict {
ok: boolean;
text: string;
}
const PIN_DIFF = [
'--- a/lib/pinInput.ts',
'+++ b/lib/pinInput.ts',
'- src: z.string().startsWith("/pins/", "The image must live in /pins/."),',
'+ src: z.union([z.string().startsWith("/pins/"), z.url()], "An image from /pins/ or a full address."),',
];
const BRANCH_DIFF = [
'commit 1: feat(pins): saving pins on boards',
'commit 2: test(boards): tests for canSavePins',
'(saved commits only; changes made before git commit do not get here)',
];
const SOURCE_CMD: Record<Source, string> = {
cached: 'git diff --cached',
worktree: 'git diff',
branch: 'git diff main...HEAD',
};
const PROMPT: Record<Task, string> = {
review: '"Review these changes. Answer with a list: file:line | problem | suggestion."',
write: '"Write Vitest tests for @lib/plural.ts and save them in lib/plural.test.ts."',
};
export function stdinFor(source: Source, staged: boolean): string[] {
if (source === 'cached') return staged ? PIN_DIFF : [];
if (source === 'worktree') return staged ? [] : PIN_DIFF;
return BRANCH_DIFF;
}
export function buildCommand(c: Config): string {
const parts: string[] = [];
if (c.task === 'review') parts.push(SOURCE_CMD[c.source], '|');
parts.push('claude');
if (c.bare) parts.push('--bare');
parts.push('-p', PROMPT[c.task]);
if (c.sonnet) parts.push('--model sonnet');
if (c.tools === 'read') parts.push('--tools "Read"');
if (c.tools === 'none') parts.push('--tools ""');
if (c.mode !== 'manual') parts.push('--permission-mode ' + c.mode);
if (c.allowWrite) parts.push('--allowedTools "Write"');
if (c.output !== 'text') parts.push('--output-format json');
if (c.output === 'schema') parts.push('--json-schema "$(cat scripts/review-schema.json)"');
if (c.output === 'json') parts.push("| jq -r '.result'");
if (c.output === 'schema') parts.push("| jq -c '.structured_output.findings[]'");
return parts.join(' ');
}
export function inputVerdict(c: Config): Verdict {
if (c.task === 'write') return { ok: true, text: 'No pipe: Claude gets only the request and reaches for the file itself.' };
const lines = stdinFor(c.source, c.staged);
if (lines.length === 0) {
return { ok: false, text: 'Empty diff: Claude gets only the request and will confidently tell you about nothing.' };
}
return { ok: true, text: 'Claude gets the request and ' + lines.length + ' lines of input.' };
}
export function toolsVerdict(c: Config): Verdict {
const write = c.task === 'write';
if (c.tools === 'none') {
return { ok: !write, text: 'No tools: Claude sees only the request and the input, and answers in one turn.' + (write ? ' It will not write the file.' : '') };
}
if (c.tools === 'read') {
return { ok: !write, text: 'Read only: Claude reads the project files.' + (write ? ' The Write tool is not in the set, so it will not write the file.' : '') };
}
if (!write) return { ok: true, text: 'Full toolset: Claude can read the project and run read-only commands.' };
if (c.allowWrite) return { ok: true, text: 'Write approved by --allowedTools: lib/plural.test.ts is created without asking.' };
if (c.mode === 'acceptEdits') {
return { ok: true, text: 'acceptEdits: Claude writes files in the project without asking. Run it only on a clean Git tree.' };
}
return { ok: false, text: 'Write rejected: it lands in permission_denials, the file does not exist, and the exit code is 0.' };
}
export function authVerdict(bare: boolean, auth: Auth): Verdict {
if (bare) {
if (auth === 'apiKey') return { ok: true, text: '--bare with an API key: you pay for tokens, and hooks, skills, MCP and CLAUDE.md stay in port.' };
return { ok: false, text: '--bare does not read the login or CLAUDE_CODE_OAUTH_TOKEN: without ANTHROPIC_API_KEY the run ends with an error.' };
}
if (auth === 'apiKey') return { ok: true, text: 'ANTHROPIC_API_KEY in -p mode is always used: you pay for tokens despite the subscription.' };
if (auth === 'oauthToken') return { ok: true, text: 'Token from claude setup-token: the run uses up your subscription limit.' };
return { ok: true, text: 'Login from /login: the subscription limit. Without --bare, the project hooks and .mcp.json run too.' };
}
export function outputVerdict(c: Config): Verdict {
const model = c.sonnet ? 'The cheaper Sonnet for routine work. ' : 'The model from your settings, that is, your last choice from /model. ';
if (c.output === 'text') return { ok: true, text: model + 'Plain text: good for the eye, brittle for a script.' };
if (c.output === 'json') return { ok: true, text: model + 'The answer is in the result field, with the cost and permission_denials next to it.' };
return { ok: true, text: model + 'A result that follows the schema is in the structured_output field. Check that the field exists.' };
}
const START: Config = {
task: 'review',
source: 'cached',
staged: true,
tools: 'none',
mode: 'manual',
allowWrite: false,
sonnet: true,
bare: false,
auth: 'subscription',
output: 'text',
};
function Choice<T extends string>(props: { label: string; value: T; options: [T, string][]; onChange: (v: T) => void }) {
return (
<label className="flex flex-col gap-1 text-sm">
<span className="font-semibold">{props.label}</span>
<select
className="rounded border border-slate-600 bg-slate-900 p-1"
value={props.value}
onChange={(e) => props.onChange(e.target.value as T)}
>
{props.options.map(([v, text]) => (
<option key={v} value={v}>{text}</option>
))}
</select>
</label>
);
}
function Row({ title, verdict }: { title: string; verdict: Verdict }) {
return (
<li className="rounded border border-slate-700 p-2">
<strong className={verdict.ok ? 'text-emerald-400' : 'text-amber-400'}>{title}</strong>
<p className="text-sm">{verdict.text}</p>
</li>
);
}
export default function App() {
const [c, setC] = useState<Config>(START);
const set = <K extends keyof Config>(key: K, value: Config[K]) => setC({ ...c, [key]: value });
const stdin = c.task === 'review' ? stdinFor(c.source, c.staged) : [];
return (
<div className="min-h-screen space-y-4 bg-slate-950 p-4 text-slate-100">
<h1 className="text-xl font-bold">A watch without a conversation: claude -p in Treasure Map</h1>
<div className="grid gap-3 md:grid-cols-3">
<Choice label="Task" value={c.task} onChange={(v) => set('task', v)} options={[['review', 'Diff review'], ['write', 'Writing a test file']]} />
<Choice label="Pipe source" value={c.source} onChange={(v) => set('source', v)} options={[['cached', 'git diff --cached'], ['worktree', 'git diff'], ['branch', 'git diff main...HEAD']]} />
<Choice label="Tools (--tools)" value={c.tools} onChange={(v) => set('tools', v)} options={[['default', 'default'], ['read', '"Read"'], ['none', '""']]} />
<Choice label="Permission mode" value={c.mode} onChange={(v) => set('mode', v)} options={[['manual', 'Manual (default in -p)'], ['acceptEdits', 'acceptEdits'], ['dontAsk', 'dontAsk']]} />
<Choice label="Login" value={c.auth} onChange={(v) => set('auth', v)} options={[['subscription', 'subscription (/login)'], ['apiKey', 'ANTHROPIC_API_KEY'], ['oauthToken', 'CLAUDE_CODE_OAUTH_TOKEN']]} />
<Choice label="Output" value={c.output} onChange={(v) => set('output', v)} options={[['text', 'text'], ['json', 'JSON and jq'], ['schema', '--json-schema and jq']]} />
</div>
<div className="flex flex-wrap gap-4 text-sm">
<label className="flex items-center gap-2"><input type="checkbox" checked={c.staged} onChange={(e) => set('staged', e.target.checked)} />I ran git add</label>
<label className="flex items-center gap-2"><input type="checkbox" checked={c.allowWrite} onChange={(e) => set('allowWrite', e.target.checked)} />--allowedTools "Write"</label>
<label className="flex items-center gap-2"><input type="checkbox" checked={c.sonnet} onChange={(e) => set('sonnet', e.target.checked)} />--model sonnet</label>
<label className="flex items-center gap-2"><input type="checkbox" checked={c.bare} onChange={(e) => set('bare', e.target.checked)} />--bare</label>
</div>
<pre className="overflow-x-auto whitespace-pre-wrap rounded bg-slate-900 p-2 font-mono text-xs">{buildCommand(c)}</pre>
<section>
<h2 className="font-semibold">What flows into the input</h2>
<pre className="rounded bg-slate-900 p-2 font-mono text-xs">{stdin.length ? stdin.join('\n') : '(nothing)'}</pre>
</section>
<ul className="space-y-2">
<Row title="Input" verdict={inputVerdict(c)} />
<Row title="Tools and writing" verdict={toolsVerdict(c)} />
<Row title="Login and bill" verdict={authVerdict(c.bare, c.auth)} />
<Row title="Model and output" verdict={outputVerdict(c)} />
</ul>
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which flag leaves Claude only the Read tool in a claude -p run?
2. A script runs claude -p "Write Vitest tests for @lib/plural.ts and save them in lib/plural.test.ts." with no permission flag. What happens?
These are 2 of 10 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Click in order
Click the items in order to build the command that creates a long-lived subscription token for CI:
- Click in order
Click the items in order to append a new request to the run whose identifier you saved in the ID variable:
- Horizontal ordering
Arrange the command that passes the changes of the whole branch to Claude and saves the answer to a file:
- Horizontal ordering
Arrange the command that forces the shape of the review with a schema and prints every problem on its own line:
- Click in order
Click the items in order to build the command that shows in readable text what your runs log in with:
- Click in order
Click the items in order to build a run in which writing a file is approved in advance:
- Code editor
In commands.sh write the code-review.sh script: get the staged changes (git diff --cached), pipe them into claude -p and ask it to point out bugs and security issues.
- Click in order
Click the items in order to build a run in which Claude sees only the request and the input from the pipe:
- Horizontal ordering
Arrange the command that gives Claude a view into a second project (remember that --add-dir accepts several directories):
Tasks after this lesson
- QuestionQuiz: The toolset in -p mode
- QuestionQuiz: Writing a file without consent in -p
- Click in orderSequence: A subscription token for CI
- QuestionQuiz: The --bare flag
- Click in orderSequence: Returning to a run by its identifier
- Put in orderOrdering: A branch diff into a file
- Put in orderOrdering: A review with a JSON schema
- QuestionQuiz: ANTHROPIC_API_KEY in -p mode
- QuestionQuiz: Someone else's project and -p mode
- Click in orderSequence: Checking the login
- QuestionQuiz: The staged diff
- QuestionQuiz: The empty diff
- Click in orderSequence: An approved write in -p
- Coding taskPractice: Pre-commit review script
- QuestionQuiz: The shape of the answer
- QuestionQuiz: The model in a script
- Click in orderSequence: A run without tools
- QuestionQuiz: Returning to a -p run
- Put in orderOrdering: A second project through --add-dir