TL;DR
Claude Code can run unattended, not just interactively. The same agent loop is available non-interactively through claude -p (headless mode), inside GitHub Actions, on a schedule via routines or desktop tasks, and as an in-session poll with /loop. This guide shows the real commands and configuration, and how to pick the right tool and the right permission scope for each.
Key points:
- Headless mode (
claude -p) reads stdin and writes stdout, so it composes with any shell pipeline, script, or CI step.
--output-format json returns a structured result (with session ID, usage, and total_cost_usd) you can parse with jq.
- Permissions are the safety boundary: scope
--allowedTools or pass a --permission-mode instead of running wide open.
- Choose where automation runs by where the work lives: CLI session, CI pipeline, your machine, or Anthropic-managed cloud.
What "process automation" means here
A process worth automating is repeatable, has a clear definition of done, and runs without a human in the loop. With Claude Code that means three building blocks:
- A self-contained prompt. The run is autonomous, so the prompt must state what to do and what success looks like. It cannot ask clarifying questions mid-run.
- A scoped permission set. Decide up front which tools the run may use without prompting.
- A trigger. A pipe in a script, a GitHub event, a cron schedule, or an HTTP call.
The rest of this guide covers each block with verifiable commands from the Claude Code docs.
Headless mode: claude -p
Add -p (or --print) to any claude command to run it non-interactively. It reads stdin and writes stdout like a normal Unix tool, so you can pipe data in and redirect output:
# Ask a one-off question about the codebase
claude -p "What does the auth module do?"
# Pipe a build log in and write the explanation out
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
# Summarize recent history
git log --oneline -20 | claude -p "summarize these recent commits"
For CI and scripts, add --bare. Bare mode skips auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md, so you get the same result on every machine and only the flags you pass explicitly take effect. In bare mode Claude has access to the Bash, file read, and file edit tools, and Anthropic authentication must come from ANTHROPIC_API_KEY (or an apiKeyHelper in --settings):
claude --bare -p "Summarize this file" --allowedTools "Read"
Auto-approve only what the task needs
Unattended runs cannot answer permission prompts, so you decide in advance. Use --allowedTools to allow specific tools, or set a baseline with --permission-mode:
# Allow exactly the tools a test-fix loop needs
claude -p "Run the test suite and fix any failures" \
--allowedTools "Bash,Read,Edit"
# Use permission-rule syntax to scope a commit task to git commands only
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 *)"
acceptEdits lets Claude write files without prompting and auto-approves common filesystem commands such as mkdir, touch, mv, and cp. dontAsk denies anything not in your permissions.allow rules or the read-only command set, which is useful for locked-down CI. Other shell commands and network requests still need an explicit allow entry, or the run aborts when one is attempted.
Structured output for scripts
Use --output-format to control the response shape: text (default), json (structured result with session ID and metadata), or stream-json (newline-delimited events for real-time streaming). The JSON payload includes total_cost_usd so you can track spend per invocation:
# Parse the text result with jq
claude -p "Summarize this project" --output-format json | jq -r '.result'
# Enforce a schema and read the structured_output field
claude -p "Extract the main function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
| jq '.structured_output'
Use it as a project linter
Because -p composes with package.json scripts, you can ship Claude as a project-specific check. Piping the diff means Claude does not need Bash permission to read it:
{
"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.\""
}
}
Chain runs across steps
Use --continue to continue the most recent conversation, or capture a session ID and pass it to --resume for a specific one. Run both from the same directory: session ID lookup is scoped to the current project directory and its git worktrees.
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"
GitHub Actions: automate on repo events
The Claude Code GitHub Action runs the same agent inside your CI. With an @claude mention in a PR or issue, Claude can analyze code, implement features, fix bugs, and open PRs. The quickest setup is to run /install-github-app from the terminal, which guides you through installing the GitHub app and adding the ANTHROPIC_API_KEY secret. You must be a repository admin.
A minimal workflow that responds to @claude mentions in comments:
name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
jobs:
claude:
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Responds to @claude mentions in comments
For scheduled or fully automated work, supply a prompt and pass CLI flags through claude_args. The action auto-detects interactive vs. automation mode based on whether a prompt is present:
name: Daily Report
on:
schedule:
- cron: "0 9 * * *"
jobs:
report:
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: "Generate a summary of yesterday's commits and open issues"
claude_args: "--model opus"
claude_args accepts any Claude Code CLI argument, for example --max-turns 5, --model, --mcp-config, and --allowedTools. Always reference the key as ${{ secrets.ANTHROPIC_API_KEY }} rather than hardcoding it, and set --max-turns plus a workflow timeout to bound cost and runtime.
Scheduling: pick where the work runs
Claude Code offers four ways to run a task automatically. Choose by where the task needs to live and what it must reach.
| Option |
Where it runs |
Triggers |
Best for |
| Routines |
Anthropic-managed cloud infrastructure |
Schedule (cron), API (HTTP POST), GitHub events |
Tasks that should run even when your computer is off; combine multiple triggers on one routine |
| Desktop scheduled tasks |
Your machine, via the desktop app |
Schedule |
Tasks needing direct access to local files, tools, or uncommitted changes |
| GitHub Actions |
Your CI pipeline |
Repo events, cron |
Work tied to repo events (opened PRs), or schedules that live alongside workflow config |
/loop |
The current CLI session |
In-session interval |
Quick polling while a session is open |
/loop polls within an open session; tasks stop when you start a new conversation, and --resume or --continue restore unexpired ones. Routines are in research preview and available on Pro, Max, Team, and Enterprise plans with Claude Code on the web enabled; create them at claude.ai/code/routines or from the CLI with /schedule.
Routine triggers in practice
A routine packages a prompt, one or more repositories, an environment, and connectors, then attaches one or more triggers. A schedule trigger has a minimum interval of one hour. An API trigger gives the routine a dedicated /fire endpoint you POST to with a bearer token, passing optional text for run-specific context such as an alert body:
curl -X POST https://api.anthropic.com/v1/claude_code/routines/trig_01ABCDEFGHJKLMNOPQRSTUVW/fire \
-H "Authorization: Bearer sk-ant-oat01-xxxxx" \
-H "anthropic-beta: experimental-cc-routine-2026-04-01" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{"text": "Sentry alert SEN-4521 fired in prod. Stack trace attached."}'
A GitHub trigger starts a session on repository events (pull request or release actions) and supports filters such as base branch, labels, draft state, and merged state. By default routines can only push to claude/-prefixed branches, which keeps protected branches safe unless you explicitly enable unrestricted branch pushes.
Worked example: triage and fix CI failures
A realistic engineering process: when a deploy reports an error, get a draft fix instead of starting from a blank terminal. Two ways to wire it up.
In CI, as a follow-up step that pipes the failing log into a scoped headless run:
cat ci-failure.log | claude --bare -p \
"Correlate this failure with recent commits and propose a minimal fix. Output only a unified diff." \
--allowedTools "Read,Bash(git log *),Bash(git diff *)" \
--output-format json | jq -r '.result' > proposed-fix.diff
As an alert-triage routine: your monitoring tool POSTs to the routine's API endpoint when an error threshold is crossed, passing the alert body as text. The routine pulls the stack trace, correlates it with recent commits, and opens a draft pull request with a proposed fix and a link back to the alert, so on-call reviews a PR instead of an empty prompt.
Practical guidance
- Write prompts for autonomy. Be explicit about success and what to do with results, for example: "Review open PRs labeled
needs-review, leave inline comments on any issues, and post a summary in the #eng-reviews Slack channel." The task cannot ask follow-up questions.
- Default to least privilege. Start from the narrowest
--allowedTools set, widen only when a run actually needs more, and prefer dontAsk for locked-down CI.
- Pipe data instead of granting Bash. Piping a diff or log into stdin avoids handing Claude permission to read it.
- Bound cost and runtime. Use
--max-turns, workflow timeouts, and --output-format json (which reports total_cost_usd) to track and cap spend.
- Use
--bare for reproducible runs. It avoids picking up whatever hooks, MCP servers, or CLAUDE.md happen to be configured locally.
- A green routine status is not a success signal. It only means the session started and exited without an infrastructure error. Open the run transcript to confirm the task actually completed.
Prerequisites
- Claude Code installed and authenticated. Headless
--bare runs and CI need ANTHROPIC_API_KEY (or Bedrock/Vertex/Foundry provider credentials); routines need a claude.ai subscription login.
- For GitHub Actions: repository admin access to run
/install-github-app and add the ANTHROPIC_API_KEY secret.
- For routines: a Pro, Max, Team, or Enterprise plan with Claude Code on the web enabled.
jq is handy for parsing --output-format json.
Troubleshooting
- A
-p run aborts when it hits a tool. A shell command or network request was attempted that is not covered by --allowedTools or your permission mode. Add the specific tool/command rule, or pick a permission mode that allows it.
- CI runs behave differently than local. Local context (hooks, MCP servers,
CLAUDE.md) may be leaking in. Add --bare so only explicit flags take effect, and pass context with --mcp-config, --settings, or --append-system-prompt.
- Piped input fails on large files. Piped stdin is capped at 10MB. Write the content to a file and reference its path in the prompt instead of piping it.
- Claude does not respond to
@claude in GitHub. Verify the GitHub App is installed, workflows are enabled, the ANTHROPIC_API_KEY secret is set, and the comment contains @claude (not /claude).
/schedule returns "Unknown command". It requires a claude.ai subscription login. Remove ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN from your shell (and any apiKeyHelper in settings.json), since these take precedence over a claude.ai login. You can always manage routines at claude.ai/code/routines.
- A routine cannot reach your service. The Default environment uses Trusted network access and blocks arbitrary hosts (
403, x-deny-reason: host_not_allowed). Add the domain under the environment's network access settings, or use an MCP connector, whose traffic is routed through Anthropic's servers.
Next steps
- {"task": "Wrap one repeatable check (typo lint, dependency audit) in a
claude -p script", "description": ""}
- {"task": "Add
--output-format json and parse the result with jq in that script", "description": ""}
- {"task": "Run
/install-github-app and add a workflow that responds to @claude", "description": ""}
- {"task": "Pick a scheduling option from the table for one recurring task and set it up", "description": ""}
- {"task": "Scope every automated run with the narrowest --allowedTools or permission mode", "description": ""}
See the headless mode, common workflows, GitHub Actions, and routines docs for the full reference.