Shell Scripts Collection
Ready-to-use shell scripts and automation tools to streamline your Gemini CLI workflow.
Getting Started with Scripts
Gemini CLI is not just an interactive tool — it is a first-class command-line program that reads from stdin, writes to stdout, and returns standard exit codes. This design makes it trivially composable with every other Unix utility you already know: find, xargs, awk, jq, and shell loops all work exactly as you would expect.
The biggest benefit of scripting Gemini CLI is repeatability. Instead of typing the same prompt every morning to review overnight log files, you write it once, schedule it with cron, and receive a formatted summary in your inbox. Instead of manually asking Gemini to add docstrings to each new function, you wire it into a pre-commit hook so the improvement happens automatically before every commit.
Before writing any script, make sure you have exported your API key as an environment variable. Add the following line to your ~/.bashrc or ~/.zshrc so the key is available in every terminal session:
# ~/.bashrc or ~/.zshrc
export GEMINI_API_KEY="your_api_key_here"
Script Categories
Setup & Installation
Scripts for initial setup and configuration
Batch Processing
Process multiple files and directories
Development Tools
Helper scripts for development workflow
Quick Setup Script
This script installs Gemini CLI globally via npm, verifies the installation, and writes a minimal configuration file. Run it once on a fresh machine or CI runner to get a fully functional environment in under 30 seconds.
#!/bin/bash
# Gemini CLI Quick Setup Script
# Usage: bash setup-gemini.sh
set -euo pipefail
# 1. Install Gemini CLI
echo "Installing Gemini CLI..."
npm install -g @google/gemini-cli
# 2. Verify installation
if ! command -v gemini &>/dev/null; then
echo "ERROR: gemini binary not found in PATH" >&2
exit 1
fi
# 3. Write default config
mkdir -p "$HOME/.gemini"
cat > "$HOME/.gemini/config.json" <<EOF
{
"model": "gemini-2.0-flash",
"temperature": 0.7,
"maxOutputTokens": 8192
}
EOF
echo "Setup complete! Run: gemini --version"
Expected output: Setup complete! Run: gemini --version followed by a version string such as 1.x.x.
Batch File Processing Script
When you have dozens or hundreds of files that all need the same AI treatment — adding docstrings, translating comments, or extracting metadata — a loop-based batch script saves enormous amounts of time. The script below iterates over every JavaScript file under a target directory and asks Gemini to add JSDoc comments in place.
The key safety mechanism here is writing the AI output to a temporary file first and only replacing the original after verifying the output is non-empty. This prevents accidentally truncating a file if the API call fails or returns an empty response due to a rate limit.
#!/bin/bash
# Batch docstring generation
# Usage: bash add-docs.sh ./src
TARGET_DIR="${1:-.}"
DELAY=2 # seconds between requests
find "$TARGET_DIR" -name "*.js" -not -path "*/node_modules/*" | while read -r file; do
echo "Processing: $file"
tmpfile=$(mktemp)
if gemini "Add JSDoc comments to every exported function. Return the full file." < "$file" > "$tmpfile" 2>&1; then
if [ -s "$tmpfile" ]; then
mv "$tmpfile" "$file"
echo " Done: $file"
else
echo " WARN: empty output for $file, skipping"
rm -f "$tmpfile"
fi
else
echo " ERROR processing $file"
rm -f "$tmpfile"
fi
sleep "$DELAY"
done
echo "Batch complete."
Input: any directory with .js files. Output: same files in place with JSDoc comments added.
Retry with Exponential Backoff
Production scripts must handle transient API errors gracefully. The most common failure modes are HTTP 429 (rate limit exceeded) and HTTP 503 (service temporarily unavailable). The following reusable helper function wraps any Gemini CLI invocation with automatic retry logic. It doubles the wait time after each failure and gives up after five attempts.
Adding a random jitter of up to one second prevents thundering-herd problems when multiple script instances run in parallel — for example, across GitHub Actions matrix jobs.
#!/bin/bash
# gemini_with_retry <prompt> [<stdin_file>]
gemini_with_retry() {
local prompt="$1"
local input_file="${2:-}"
local max_attempts=5
local delay=2
for attempt in $(seq 1 $max_attempts); do
if [ "$input_file" = "-" ]; then
gemini "$prompt" && return 0
else
gemini "$prompt" < "$input_file" && return 0
fi
local jitter=$(( RANDOM % 1000 ))
echo "Attempt $attempt failed. Retrying in ${delay}s..." >&2
sleep "$(echo "$delay + $jitter / 1000" | bc)"
delay=$(( delay * 2 ))
done
echo "ERROR: all $max_attempts attempts failed" >&2
return 1
}
# Example usage
gemini_with_retry "Summarize this file" ./README.md
Pre-Commit Code Review Hook
A Git pre-commit hook that asks Gemini to review only the staged diff gives you a lightweight AI code review on every commit. The hook extracts the staged diff with git diff --cached, sends it to Gemini, and prints the feedback. If Gemini finds critical issues it returns the word BLOCK on the last line and the hook exits with a non-zero status, preventing the commit.
#!/bin/bash
# .git/hooks/pre-commit
# chmod +x .git/hooks/pre-commit
DIFF=$(git diff --cached --no-color)
if [ -z "$DIFF" ]; then
exit 0
fi
REVIEW=$(echo "$DIFF" | gemini \
"Review this git diff for bugs, security issues, and style problems. \
End your response with BLOCK if any critical issues are found, or PASS otherwise.")
echo "--- Gemini Review ---"
echo "$REVIEW"
echo "---------------------"
if echo "$REVIEW" | tail -1 | grep -q "BLOCK"; then
echo "Commit blocked by Gemini review." >&2
exit 1
fi
exit 0
Install by saving to .git/hooks/pre-commit and running chmod +x .git/hooks/pre-commit.
Frequently Asked Questions
How do I run a Gemini CLI shell script on Windows?
On Windows, use Git Bash or WSL (Windows Subsystem for Linux) to run bash scripts. Alternatively, convert the script to a PowerShell equivalent or use Node.js to wrap the Gemini CLI calls. Most developers find WSL the easiest path because it provides a full Linux environment.
Can I chain multiple Gemini CLI commands in a script?
Yes. You can pipe the output of one gemini command into another using standard Unix pipes, or store intermediate results in shell variables and reference them in subsequent calls. This makes it easy to build multi-step AI pipelines — for example, summarize a file, then translate the summary.
How do I handle API rate limit errors inside a script?
Implement exponential backoff: catch the 429 HTTP error and retry after an increasing delay (2s, 4s, 8s, etc.). The retry helper script in this page demonstrates the pattern. A maximum of five retries with random jitter handles most transient failures.
Is it safe to put my API key directly in a shell script?
No. Always store your API key in an environment variable such as GEMINI_API_KEY and reference it in the script. Never hard-code secrets or commit them to version control. Use a.env file together with a tool like direnv for local development.
How do I test a script without consuming real API quota?
Set the GEMINI_MODEL environment variable to a free-tier model such asgemini-2.0-flash during testing. You can also mock the gemini binary in CI with a shell function that echoes a fixed response, letting you validate the script logic without hitting the real API.