Claude Code Headless Mode Scripts: Batch and Scheduled Tasks

Claude Code Headless Mode Scripts: Batch and Scheduled Tasks

How to run Claude Code headless mode in scripts and scheduled jobs: limited tools, structured output, a log for every run and human review of results.

••

Want to apply this in your company?

Book a call with Juan →

Claude Code Headless Mode Scripts: Batch and Scheduled Tasks

Claude Code headless mode runs the tool without the interactive interface: you pass a prompt on the command line, it does the work and hands the result back to your script, with no live conversation. To use it in batches or scheduled jobs, decide in advance which tools it may use, how many steps it may take and where each run will be recorded. Without those three limits, what you have is an autonomous process that nobody is watching.

Key takeaways

  • Headless mode runs one prompt per execution and then exits, which makes it a good fit for scripts, scheduled tasks and CI steps.
  • With nobody present to approve permission requests, the allowed-tools list becomes your main safety barrier.
  • Structured output (JSON) and a log per run turn the automation into something you can audit, repeat and debug.
  • Results should land somewhere reviewable, such as a draft or a proposed change, and not go straight to production.
  • Start with one small workflow and an agreed success criterion before scheduling anything to run on its own.

What is headless mode and when does it make sense?

In interactive use, a person follows every step, reads what Claude Code proposes and approves or denies actions. In headless mode that person steps out. You call the command with the print option (usually written as -p) and a prompt, the agent does what is needed and prints the result. It is the same agent, but operating inside a script, so responsibility for control moves from the conversation to the configuration.

The payoff shows up when the task is repetitive, has a clear input and produces output you can verify. Some examples: checking a batch of files against a team standard, drafting release notes from commits, classifying support tickets exported from a system, updating documentation passages or summarizing failures from a test run.

A quick decision guide:

  • Use headless if the task repeats, the input is predictable and someone can check the result in a few minutes.
  • Use headless if the worst realistic error is a poor draft that will be discarded during review.
  • Prefer interactive mode if the task needs exploration, questions back to you or decisions along the way.
  • For now, do not automate tasks with financial, legal or reputational impact unless a person approves before the final action.

For the boundary of what should not be delegated, read also Guardrails for AI Agents: Input, Output and Action Controls.

How do you run Claude Code in a script, step by step?

Exact option names change between versions, so confirm them in the official documentation for the version you have installed. The overall design, however, is stable.

  • Write the prompt as a specification: the goal, the input files or data, the expected output format and what to do when information is missing (for example, return an empty field and a justification).
  • Keep the prompt in a versioned file in the repository, not inside the script, so changes have history and review.
  • Call Claude Code with the print option and ask for JSON output, so your script reads fields instead of interpreting free text.
  • Define the allowed-tools list and a maximum number of turns (agent steps) for the run.
  • Run from a controlled working directory containing only the files the task needs.
  • Read the process exit code. If it signals failure, the script logs it and alerts a person, instead of retrying without limit.
  • Validate the output before using it: does the JSON have the expected fields? Are the values within an acceptable range? Only then does the result move forward.

As the workflow grows, project rules (conventions, test commands, off-limits areas) belong in a repository instructions file, and recurring tasks can become reusable skills. See Claude Code Skills: How to Create Them for Your Team and How to Write a Good CLAUDE.md for Your Company Repository for that layer.

How do you limit what an unattended run can do?

With nobody to click approve, anything not explicitly allowed should be denied or simply not run. Treat the permissions configuration as the contract of the automation. The most useful controls are:

  • Allowed-tools list: permit only what is necessary. A read-and-summarize task does not need disk writes or network access.
  • Denied-tools list: explicitly block what must never happen, such as deleting files, changing deployment configuration or running arbitrary network commands.
  • Turn limit: caps how many steps the agent takes, which contains loops and tasks that drift out of scope.
  • Conservative permission mode: avoid any mode that skips confirmations outside an isolated, disposable environment.
  • Isolation: run in a container or single-use machine with no access to the internal network beyond what is strictly required.
  • Minimal credentials: use read-only keys scoped to what the task touches, stored in the scheduler's secrets manager and never in the repository.
  • MCP integrations: connect only audited servers and, preferably, with read access. This is covered in Configure MCP in Claude Code: Local, Project and User Scopes.

Batch automations carry a specific risk: the agent reads content you did not write, such as emails, tickets, web pages and comments. That content can contain instructions disguised as data. OWASP's guidance on preventing prompt injection applies here: separate instructions from data, do not give the agent tools that malicious text could use to cause harm and validate the output before acting. For an overview of permissions, sandboxing and secrets in a company setting, see Claude Code Security: Permissions, Sandbox and Secrets for Teams.

What should you record for each run?

An automation without records becomes a black box: when something looks off, nobody knows what was requested, what was read and what was produced. Record, per run:

  • A unique run identifier, date, time and duration.
  • The prompt version (the commit hash of the file works) and the Claude Code version used.
  • A reference to the input, such as the batch name or item identifiers, and not the full content when it includes personal data.
  • The tools allowed in that run and the turn limit.
  • The structured output returned and the validation result.
  • The exit code, errors and number of attempts.
  • Who reviewed the result and what the decision was: accepted, adjusted or discarded.

JSON output usually includes run metadata, such as a session identifier and usage information, which helps build this record. To follow a long run in real time, there is also a streaming output format. Confirm which fields are available in the documentation for your version before depending on them.

If your company already has observability in place, send these events to the same place. The OpenTelemetry observability primer is a good conceptual base on logs, metrics and traces, and semantic conventions for generative AI are in development.

A data protection note (LGPD in Brazil, and similar rules elsewhere): the log is also data processing. If inputs contain personal data, define what goes into the record, how long it is kept and who can access it. When in doubt, log references and not content.

How do you schedule runs without losing control?

The scheduler can be a cron job on a server, a CI routine or an orchestration tool your company already uses. What matters is the behavior around the command:

  • Concurrency lock: prevent two runs of the same workflow from processing the same items at the same time.
  • Maximum runtime: if a run exceeds the limit, the process is terminated and a person is alerted.
  • Safe reruns: design so that repeating the task does not duplicate effects. The concept of idempotency, well explained in Stripe's documentation on idempotent requests, applies equally to AI batches: each processed item has a key, and items already completed are skipped.
  • State between runs: for long tasks, keep a progress file that says what has already been done. Anthropic describes this kind of practice in its material on harnesses for long-running agents.
  • Reviewable destination: output goes to a draft, a proposed change or a review queue. The step that actually changes something important stays with a person or with validated, deterministic code.
  • Failure alert: an automation that fails silently is worse than one that never existed, because it creates false confidence.

When part of the workflow is deterministic (fetching data, formatting, sending), keep it in ordinary code and call Claude Code only where judgment is needed, such as interpreting free text. This split makes the system cheaper, more predictable and easier to test.

Illustrative scenario: batch review of documentation

Imagine, as a hypothetical example, a software company with an internal documentation repository that keeps going out of date. Every week, a scheduled job runs Claude Code in headless mode over the files changed in recent days.

The prompt, versioned in the repository, asks it to flag passages that contradict the current code and to suggest fixes in a structured format. The only allowed tools are file reading and search. Editing, command execution and network access are blocked. The turn limit is low and the run happens in a disposable container.

The script validates the JSON, discards suggestions without a file reference and opens a proposed change with the remaining suggestions. A team member reviews it, accepts or rejects it and the log keeps the decision. After a few weeks, the team compares accepted and rejected suggestions, adjusts the prompt and decides whether to widen the scope, keep it as it is or switch it off. Nothing in this flow touches production without a person.

To define the success criterion for this kind of pilot, the guide How to Measure an AI Automation Pilot: Metrics and Decision Gates helps you agree on metrics and decision points before you start.

How does the map, limit, pilot and hand over method apply?

Map: describe the current process, who does it, how long it takes and which errors appear today. Without that baseline, there is no way to know whether the automation improved anything.

Limit: define the accessible data, the allowed tools, the prohibited actions and the point where a person steps in. This is the stage where the permissions list, isolation and minimal credentials are decided.

Pilot: run a single real workflow, with a record of every run and an agreed success criterion. Watch for failures, review effort and cases the prompt did not anticipate.

Hand over: give the team the versioned prompt, the configuration, the log dashboard and the shutdown procedure. After that, the decision is to expand, adjust or stop, based on what the pilot showed. None of this guarantees a result: it is a way to find out early whether the automation deserves to continue.

Frequently asked questions

Is Claude Code headless mode the same as using the Anthropic API directly? Not exactly. It runs the Claude Code agent, with its tools for reading files, searching and running commands, while the API returns only the model's response and requires you to build the agent loop yourself. For tasks that touch files and repositories, headless is usually the shortest path. For fully custom workflows, building on the API or the SDK may make more sense.

Do I need a dedicated server to run batch automations? Not necessarily. A CI job, a small virtual machine or a scheduled container already covers many cases. What matters is that the environment is isolated, keeps secrets safe and lets you retain the logs. A comparison of options is in Where to Host an AI Agent: VPS, Cloud or On-Premise Server.

Can I leave Claude Code running with no human supervision at all? Only for low-risk tasks, with very restricted tools and output validated by code. Even then, someone needs to look at the logs and alerts periodically. For any action with an external effect, such as sending a message to a customer, changing a record or publishing, keep a human approval step.

How do I stop a prompt change from degrading results without my noticing? Version the prompt, keep a small set of reference cases with the expected answer and run that check on every change, preferably in continuous integration. Compare the results before publishing the new version. The practice is detailed in Prompt Regression Testing in CI: Catch Quality Drops Before Users Do.

Sources

Claude Codeheadless modeAI automationscriptingdeveloper workflow