Skip to content

Loops and autonomous runs in Gemini CLI

Set up loops and autonomous runs in the CLI.

  • Lesson 4 of 6
  • About 9 min read
  • Quiz of 5 questions
  • +190 XP

Some coding work is just the same step on repeat until a condition is met: fix the code, run the tests, read the failure, fix again. Gemini CLI can run that whole cycle for you in an agentic loop, editing files and executing commands until the task is genuinely done or a guardrail stops it. This lesson is about running that loop deliberately, unattended, and safely.

The loop is the default, not a trick

When you give Gemini CLI a task, it does not answer once and quit. It plans, calls tools (read file, write file, run shell command), observes the result, and decides the next action. That observe-then-act cycle repeats until the model believes the goal is met.

This is the ReAct pattern (reason + act) wired into a real shell. The important shift for you: you are no longer prompting for text. You are handing over a goal and a set of tools, then letting the agent iterate against real feedback from your machine.

A single request is right when the output is the answer: "explain this function," "write a regex." A loop is right when success is defined by an external check the agent cannot fake:

  • Iterate until the test suite passes.
  • Batch the same refactor across 40 files.
  • Keep fixing lint and type errors until the build is clean.
  • Bump a dependency, then chase every breakage it causes.

The distinction is whether there is a verifiable stop condition. If there is, a loop beats a chat, because the agent grades its own work against reality.

Non-interactive runs

Interactive mode is the REPL you already know. For automation you want non-interactive (headless) mode: one command, no back-and-forth, exit when done. Use the -p (prompt) flag.

bash
gemini -p "Run the test suite with 'npm test'. If anything fails, \
read the output, fix the code, and re-run until all tests pass. \
Do not modify test files." --model flash

The agent now owns the full loop. It runs npm test, parses failures, edits source, and re-runs, cycling until green or until a guardrail trips.

The flags that matter most here:

  • --model picks the tier. Reach for Flash on tight, well-scoped loops (fast, cheap iteration). Move to Pro when the reasoning is genuinely hard: tangled failures, architecture decisions, ambiguous specs. The flash and pro aliases track the current Gemini generation, so your scripts do not break when a pinned version like gemini-2.5-flash is retired. Pin a full model ID only when you need reproducible behavior, and check the deprecation schedule when you do.
  • --yolo (or --approval-mode=yolo) auto-approves tool calls so the loop never pauses for confirmation. Powerful and dangerous. More on containing it below.
  • --output-format json returns a structured result (response, stats, errors) that a script or CI step can parse instead of scraping text.

Because it is a plain command, non-interactive mode drops straight into CI, cron, or a Git hook. That is what "autonomous" means in practice: no human in the REPL.

Scheduling and unattended triggers

There is no built-in Gemini CLI scheduler. You wire it into the tools you already run. That is a feature, not a gap: the CLI stays a composable Unix citizen.

A nightly dependency-and-test sweep via cron:

bash
# 2:00 AM daily: attempt upgrades, keep tests green, open a PR
0 2 * * * cd /srv/app && gemini -p "$(cat prompts/nightly-deps.txt)" \
  --yolo --model flash >> logs/nightly.log 2>&1

Or a GitHub Actions job triggered on a schedule or on issue labels, letting Gemini CLI triage and draft a fix branch. The pattern is identical: an external trigger fires a non-interactive run, and the run does the looping.

For the official flag reference and configuration, see the [Gemini CLI documentation](https://github.com/google-gemini/gemini-cli).

Video

Gemini CLI: Agentic coding from your terminal

walkthrough of non-interactive runs and tool approvals

Watch on YouTube

Check your reading

According to the lesson, what fundamentally distinguishes a task suited for an agentic loop from one suited for a single request?

Worked example: iterate until the build passes

Here is a clean, contained autonomous run you can adapt. It caps the work, forbids risky moves, and produces a reviewable result instead of silently pushing to main.

bash
#!/usr/bin/env bash
set -euo pipefail

BRANCH="auto/fix-build-$(date +%Y%m%d-%H%M)"
git switch -c "$BRANCH"

gemini --yolo --model flash -p '
Goal: make the build and tests pass.
Steps:
  1. Run "npm run build" and "npm test".
  2. If either fails, read the error, make the smallest fix, re-run.
  3. Repeat until both succeed.
Rules:
  - Never edit files under /tests or /node_modules.
  - Never touch package.json versions.
  - If unresolved after 8 attempts, stop and summarize what remains.
'

# Human review gate: agent branched, we decide the merge.
git push -u origin "$BRANCH"
echo "Review the PR before merging: $BRANCH"

Read what makes this safe rather than reckless:

  • The stop condition is external and objective. "Both succeed" is decided by exit codes from build and test, not by the model's opinion.
  • The attempt cap is in the prompt. "8 attempts, then stop and summarize" prevents an infinite spiral on an unfixable error.
  • Off-limits paths are explicit. The agent cannot make tests pass by deleting the tests, a classic failure mode.
  • The result lands on a branch. No autonomous run touches your main branch. A human opens and merges the PR.

That last point is the whole philosophy. Autonomy is for the labor. The merge is still yours.

Stop conditions: how loops actually end

An agentic loop terminates for one of four reasons. Design for all of them.

  1. Success. The verifiable condition is met (tests green, files processed). This is the happy path.
  2. Attempt or turn limit. You told it to stop after N tries. Always set this. Loops without a ceiling are how you discover a runaway at 3 AM.
  3. Cost or token cap. The run hits a budget you set (next section).
  4. Hard error the agent cannot recover from. Missing credentials, a command that does not exist, a permission wall.

The dangerous case is none of the above: the agent thinks it is making progress but is looping through the same broken fix. That is why "smallest fix, re-run" plus an attempt cap beats an open-ended "keep going." Bound every dimension: attempts, time, and money.

Cost caps and budget control

An unattended loop that calls a model on every turn can quietly rack up spend. Three layers of defense, from cheapest to firmest:

Pick the model to match the job. Flash handles most iterate-until-green loops at a fraction of Pro's cost. Do not send a linter-fix loop to Pro.

Bound the loop in the prompt. Fewer attempts means fewer turns means fewer tokens. A tight, specific goal converges faster than a vague one.

Watch the ceiling at the account level. When you run through the paid Gemini API or Vertex AI, set Cloud Billing budgets and alerts on the project, not just limits in your prompt. Be clear about what they do: a budget sends alerts, it does not stop spend by itself. To actually cut off usage you need an extra step, such as a budget notification that triggers a function to disable billing, or API quota limits set on the project. This is your real backstop, because prompt-level limits can be reasoned around by a confused agent and quota limits cannot.

A practical rule: never run --yolo on a paid key without budget alerts and a quota or cutoff configured first. The prompt cap protects you from logic errors. The account-level cap protects you from everything else.

Check your reading

The lesson describes Gemini CLI's default behavior as following the ReAct pattern. What does this pattern mean in this context?

Review gates for unattended work

The scarier an autonomous run's powers, the more it needs a gate between "agent finished" and "change is live." A review gate is any checkpoint where a human or an automated check must approve before the work propagates.

Layer these from least to most trusting:

1. Approval prompts (interactive)

The default. The CLI pauses before each write or shell command and asks. Great for exploration, useless for unattended runs because nobody is there to say yes.

2. Sandboxing (the container gate)

Before you reach for --yolo, contain the blast radius. Run the agent with sandboxing enabled so tool calls execute inside an isolated container, not directly on your machine. Even a confused loop cannot reach files or networks outside the box. Enable it and confine the working directory:

bash
gemini --sandbox --yolo -p "$(cat prompts/refactor.txt)"

Combine sandboxing with a scratch git checkout and the agent literally cannot harm anything you care about.

3. The branch-and-PR gate

As in the worked example: autonomous runs write to a feature branch and open a pull request. Your existing CI (tests, security scans) runs on the PR, and a human approves the merge. This is the sweet spot for most teams: full autonomy inside the loop, full control at the boundary.

4. CI as the objective judge

Do not trust the agent's "I'm done." Let your pipeline decide. The agent's job is to produce a branch that passes CI. If CI fails, the PR does not merge, full stop. This turns your existing test and lint infrastructure into the arbiter of autonomous work, which is exactly what it is good at.

Batch loops across many files

The other classic loop is not "until a condition," it is "for every item." Same mechanics, different shape.

bash
gemini --yolo --model flash -p '
For every *.py file under /src:
  - Add type hints to all public functions.
  - Run "mypy" on the file after editing.
  - If mypy errors, fix and re-check that file before moving on.
Skip files that already pass mypy cleanly. Report a table of files
changed and files skipped when finished.
'

Notice the per-item verification (mypy after each edit). That keeps the batch honest: the agent proves each file before advancing, instead of editing all 40 and hoping. When a batch is large and independent, this is dramatically better than 40 separate chat sessions, because the agent carries context and its own quality checks forward.

For structured, repeatable pipelines beyond ad-hoc CLI runs (multiple specialized agents, richer orchestration, evaluation), graduate to the Agent Development Kit (ADK). The CLI is the fast path; ADK is where production loops with proper testing and deployment live.

When a loop is the wrong tool

Autonomy is not free, so do not reach for it reflexively:

  • No objective check exists. If success is "make the copy better," there is nothing for the loop to grade against. That is a single request with human review.
  • Each step needs judgment. Migrating a payments flow is not a loop you leave running. It is a series of decisions you make with the agent, interactively.
  • The cost of a wrong autonomous action is high and no sandbox fully contains it. Then keep the human in the turn.

The loop earns its keep exactly when the check is cheap and objective and the labor is tedious. That is most of the grind in a codebase, which is why this matters.

Key Takeaways

  • Use a loop when success is externally verifiable (tests, build, lint, type checks) and the labor is repetitive. Use a single request when the output is the answer or each step needs judgment.
  • Run unattended with `gemini -p`, wire it into cron or CI for scheduling, and match the model tier to the job (Flash for tight loops, Pro for hard reasoning). Prefer the flash and pro aliases over pinned version IDs that get retired.
  • Bound every loop on three axes: attempts (in the prompt), time, and money. Cloud Billing budgets only alert, so add quota limits or an automated cutoff if you need spend to actually stop.
  • Never run `--yolo` bare. Contain it with --sandbox, and let autonomous work land on a branch and PR so your existing CI is the objective judge and a human owns the merge.
  • Forbid the cheat paths explicitly (do not edit tests, do not bump versions) so the agent cannot make the stop condition pass the wrong way.

Quiz

Did the essentials stick?

3 questions, one at a time. Each one right on the first try brings the probe closer to the planet.

Question 1 of 3

In a tight, well-scoped loop like 'keep fixing lint errors until the build is clean,' which model tier does the lesson recommend and why?