GeminiIntermediate

How to Run the Gemini CLI Non-Interactively in Scripts

Pass a prompt with the -p flag and pipe input so the Gemini CLI works inside shell pipelines and CI.

6 minIntermediate

The Gemini CLI is interactive by default, but it also runs as a one-shot command. That lets you drop it into shell scripts, git hooks, and CI jobs. This guide covers passing prompts directly, piping in file contents, and capturing the output.

What you need

  • The Gemini CLI installed and authenticated
  • A terminal comfortable with pipes and redirection
  • Optional: a Gemini API key for use in CI
  • About 5 minutes

Step 1: Pass a prompt with -p

The -p (or --prompt) flag runs a single prompt and prints the answer to stdout without opening the interactive UI. This is the building block for everything else.

zsh - one-shot
$gemini -p "List three risks of using eval in JavaScript."
1. Arbitrary code execution from untrusted input
2. No static analysis or minification benefits
3. Slower execution and harder debugging
$

Step 2: Pipe input into a prompt

You can pipe a file or command output into the CLI and reference it in your prompt. This is the fastest way to ask about a specific log, diff, or file.

terminal
git diff | gemini -p "Write a concise commit message for this diff."

cat error.log | gemini -p "What is the root cause of this stack trace?"
Use API key auth in CI
Browser sign-in does not work on a build server. Set GEMINI_API_KEY as a secret in your CI environment so the CLI authenticates without a login prompt.

Step 3: Capture output in a script

Because output goes to stdout, you can capture it in a variable or redirect it to a file. The snippet below builds a commit message from staged changes inside a shell script.

commit-msg.sh
#!/usr/bin/env bash
set -euo pipefail

msg=$(git diff --cached | gemini -p "Write a one-line conventional commit message.")
echo "Suggested: $msg"
git commit -m "$msg"
zsh - script run
$ ./commit-msg.sh
Suggested: feat(api): add pagination to /users
[main 3f9a1c2] feat(api): add pagination to /users
1 file changed, 12 insertions(+)
The script generating and using a commit message.

Result

The Gemini CLI now behaves like any other Unix tool: it reads stdin, writes stdout, and slots into pipelines. You can chain it with git, grep, and jq, or call it from CI to automate review notes and changelogs.

Watch related tutorials

Tags
#gemini-cli#automation#scripting#pipes#ci