Sub topic 15
Running agents from scripts
This chapter assumes you can write shell scripts, read exit codes, and have used at least one of the three tools interactively. It also assumes you know the permission and sandbox settings from earlier chapters.
Why run an agent without a session
An interactive session needs a person to read output and answer approval prompts. A script has no one to do that. Non-interactive mode (also called headless or print mode) runs one prompt to completion, prints the result to standard output, and exits. That lets you call an agent from a shell script, a git hook, a scheduled job, or a CI pipeline.
All three tools support this:
claude -p "Explain what the build script in package.json does"
codex exec "Explain what the build script in package.json does"
copilot -p "Explain what the build script in package.json does"The agent loop is the same as in an interactive session. It calls the model, runs tools, and reads the results until it decides it is finished. The only change is that nobody answers its questions.
What changes without a human
Three things matter in a script.
- Approvals cannot be answered. If the agent needs a permission you did not grant in advance, the run stops or the action is refused. Depending on the tool and settings, an unanswered approval can also hang the job. You must decide the allowed actions before the run starts.
- Output must be parseable. Another program reads the result, so you want plain text or structured JSON rather than formatted terminal output.
- Runs must be bounded. A loop with no person watching can use a lot of time and tokens. Set a timeout, and limit the agent's scope in the prompt.
Getting input in and output out
Pass the task as an argument. Pass data on standard input when it is large or comes from another command. Claude Code accepts piped input alongside a prompt argument:
git diff origin/main...HEAD | claude -p "Review this diff for bugs. Do not edit files."For machine-readable output, Claude Code offers --output-format json, which wraps the answer in a JSON object. Codex CLI offers --json, which prints events as JSON lines. You can extract the answer with jq:
claude -p "Summarize the open TODO comments in src/" --output-format json | jq -r '.result'Output flags change between releases, so run claude --help, codex exec --help, or copilot --help before you rely on one in a pipeline.
Granting permissions up front
In a script you grant only what the task needs. The permission and sandbox settings you saw in earlier chapters are the mechanism, and you can pass them as flags or keep them in a config file.
| Task | Safe starting point |
|---|---|
| Read-only review or explanation | Read-only sandbox, or allow only read and search tools |
| Fix code and run tests | Workspace-write sandbox, with the test command pre-approved |
| Anything touching the network or secrets | Do not automate until you have isolated it |
For example, Codex CLI can run a review in a read-only sandbox, and Copilot CLI can pre-approve one command:
codex exec --sandbox read-only "List functions in src/ that have no tests"
copilot -p "Run the tests and summarize failures" --allow-tool 'shell(npm test)'Each tool also has a flag that approves everything, such as --allow-all-tools in Copilot CLI. Treat it as a last resort. Use it only inside a disposable container or CI runner with no secrets, because a prompt injection (instructions hidden in files the agent reads) can then run any command.
A complete example: a review script
This script reviews the current branch and saves the result. It fails safely: it stops on errors, skips empty diffs, and limits the run to ten minutes.
#!/usr/bin/env bash
set -euo pipefail
base="${1:-origin/main}"
out="review.md"
if git diff --quiet "$base"...HEAD; then
echo "No changes against $base; nothing to review."
exit 0
fi
git diff "$base"...HEAD |
timeout 600 claude -p \
"Review this diff for bugs and missing tests. Reply as a bullet list. Do not edit files." \
> "$out"
echo "Review written to $out"set -euo pipefail makes the script exit if any command in the pipeline fails. Without pipefail, a failed agent run would look like success because > still succeeds. The timeout command ends the run if the agent stalls.
Using the exit code
A scripted agent is only useful if the calling program can tell whether it worked. Check two separate things:
- Did the tool run? A non-zero exit code means the tool itself failed, for example from an authentication error, a timeout, or a refused action.
- Did the task succeed? A zero exit code only means the agent finished. It does not mean the fix is correct.
For the second question, verify independently. Run your own tests after the agent returns instead of trusting its summary:
claude -p "Fix the failing test in tests/date.test.js" || exit 1
npm testAuthentication in automation
A headless run cannot open a browser login. Use the credential method your tool supports for automation, usually an API key or token passed through an environment variable. Store it in your CI system's secret store. Never put it in the script or commit it. Check each tool's documentation for the exact variable name.
Where it fits in a pipeline
Keep a person at the end of the chain. Let the agent propose, for example by opening a pull request or posting a comment, and let a human merge.
Common errors
- The job hangs. An approval prompt is waiting for input nobody can give. Pre-approve the specific command or tighten the task.
- The pipeline reports success on a failed run. You omitted
pipefail, or you ignored the exit code. - Output is hard to parse. You captured human-oriented text. Switch to the JSON output option.
- Results vary between runs. Model output is not deterministic. Write prompts that ask for a fixed format, and validate the format in the script.
- Costs grow. Large diffs and long loops use many tokens. Scope each run to one narrow task.
Exercise
A CI job runs claude -p "Fix the lint errors" > out.txt in a script without set -e or pipefail, then deploys. The agent run fails with an authentication error, yet the deploy proceeds. Name two changes that prevent this.
Show answer
First, add set -euo pipefail (or check the exit code of the agent command) so a failed run stops the script. Second, run the linter or tests yourself after the agent step and deploy only if they pass. Setting up the authentication variable correctly fixes the cause, but the first two changes keep any future failure from reaching the deploy step.
Exercise
You want a nightly job that asks an agent to list untested functions. Which permission setup fits best, and why?
Show answer
A read-only sandbox, or only read and search tools allowed. The task needs no edits and no commands that change anything, so the job should have no way to write files. If a file the agent reads contains injected instructions, the damage is limited.