Running Claude Code headless (claude -p): agents in scripts, cron and CI
TL;DR
claude -p "prompt" runs one turn and exits, printing to stdout. Add --output-format json to parse it, --allowedTools to limit permissions and --max-turns to stop runaway loops. Great for scheduled reports, automated reviews and changelogs.
Basic commands
# Summarize today's changes
git log --since=midnight --oneline | claude -p "Write a short changelog grouped by feature/fix"
# JSON output for further scripting
claude -p "List TODOs in src/ as JSON" --output-format json > todo.json
# Limit permissions + turns
claude -p "Run tests and fix lint errors" \
--allowedTools "Bash(npm test),Bash(npm run lint),Edit" --max-turns 10Real uses
| Job | Trigger |
|---|---|
| Sprint progress report from commits + tickets | Daily cron at 5pm |
| PR review against the team checklist | GitHub Actions on PR open |
| Triage last night's error logs | Cron at 7am |
| Generate release notes | On tag creation |
Running it safely
- Always pass a minimal
--allowedTools; never skip permissions on machines with real data. - Run in a dedicated container/runner with its own API key and spend limit.
- Need deeper integration (custom tools, hooks in code)? Use the Claude Agent SDK.
Docs: Headless mode · CLI reference