Skip to content

Gemini CLI Setup

Published: February 26, 2026 · Last edited: February 26, 2026

A grounded approach to setting up Gemini CLI that keeps costs visible, scope controlled, and sensitive data safe.

Core Philosophy

  • Visible costs over silent consumption
  • Explicit scope over open-ended access
  • Deliberate use over autopilot
  • Smallest context that gets the job done
  • Deny by default on agent actions

1. Installation

Requires Node.js 18+.

bash
npx @google/gemini-cli
bash
npm install -g @google/gemini-cli
bash
brew install gemini-cli

Verify the install:

bash
gemini --version

Official documentation: google-gemini.github.io/gemini-cli

Authentication

On first run, gemini walks you through authentication. Three options:

OAuth (recommended for personal use):

bash
gemini
# Opens browser for Google account login

Free tier with personal Google account: 1,000 requests/day, 60 requests/minute, access to Gemini 2.5 Pro with a 1M token context window — no billing required.

Gemini API key (usage-based billing):

bash
export GEMINI_API_KEY="your-api-key"

Get a key at aistudio.google.com/apikey. Add to ~/.zshrc or ~/.bashrc to persist it:

bash
# Gemini CLI API key
export GEMINI_API_KEY="your-api-key"

Vertex AI (enterprise):

bash
export GOOGLE_API_KEY="your-key"
export GOOGLE_GENAI_USE_VERTEXAI=true
export GOOGLE_CLOUD_PROJECT="your-project-id"

2. Core Configuration

Gemini CLI uses two layers of configuration: global (user-level) and per-project.

Global Settings

File: ~/.gemini/settings.json

Created automatically on first launch. Controls your personal preferences across all projects:

json
{
  "theme": "Default",
  "model": "gemini-2.5-pro",
  "privacy": {
    "usageStatisticsEnabled": false
  },
  "telemetry": {
    "enabled": false
  }
}

Project Settings

File: .gemini/settings.json (check into the repo)

Controls behaviour for a specific project. Team members who clone the repo get the same configuration:

json
{
  "tools": {
    "exclude": [
      "run_shell_command"
    ]
  },
  "context": {
    "fileFiltering": {
      "respectGitIgnore": true
    }
  }
}

Start by excluding what the task does not need. A session reviewing documentation does not need shell execution. Exclude it rather than relying on Gemini's judgment.

Ignore File

Create .geminiignore in your project root to prevent Gemini from reading irrelevant files — the same syntax as .gitignore:

# .geminiignore
node_modules/
dist/
build/
*.lock
*.log
coverage/
.env
.env.*
secrets/

Project Instructions File

File: GEMINI.md at the root of your project.

Gemini reads this at the start of every session. Treat it like onboarding notes for a careful contractor — describe the project, the conventions, and the constraints.

markdown
# Project Context

## What This Is
[One paragraph describing the project]

## Tech Stack
- Language:
- Framework:
- Test runner:
- Linter:

## Conventions
- Branch naming: feature/*, fix/*, chore/*
- Commit style: conventional commits (feat, fix, docs, etc.)
- Tests must pass before committing

## What Gemini Should NOT Do
- Push to remote without asking
- Modify database migration files
- Change environment files directly
- Install new dependencies without discussion

## Common Commands
- Run tests: `npm test`
- Lint: `npm run lint`
- Build: `npm run build`

Hierarchy: GEMINI.md files are loaded in order — global (~/.gemini/GEMINI.md), then ancestor directories, then project root, then subdirectories. More specific files override general ones. Use the global file for conventions that apply everywhere; project-level files for project-specific rules.

Keep GEMINI.md short. A long file means Gemini spends tokens reading instructions instead of doing work.

Use /memory refresh to reload context files mid-session, and /memory show to inspect exactly what context is loaded.

3. Monitoring Tokens

Tokens are currency. Every file read, every large paste, every long conversation costs them. Visibility into consumption is not optional — it is how you stay in control.

Check Usage

Type /stats at any point in a session to see token usage for the current conversation.

Compress History

When the context grows long, the CLI can automatically compress conversation history. You can configure the compression threshold as a fraction of the model's total token limit:

json
{
  "model": {
    "summarizeToolOutput": {
      "tokenBudget": 0.6
    }
  }
}

A value of 0.6 triggers compression when history exceeds 60% of the model's limit. Adjust downward if you want earlier compression to keep costs predictable.

Avoid Reading Entire Codebases

Be deliberate about what files Gemini reads:

bash
# Point it at specific files
gemini "Look at src/services/payment.ts and explain the retry logic"

# Avoid vague prompts that trigger broad file reads
# "Look at the codebase and find all bugs" — this reads everything

Things That Silently Consume Tokens

  • Entire log files passed as context
  • Generated files (lock files, build artifacts)
  • Large test fixtures or JSON blobs
  • Files not excluded in .geminiignore

Add these to .geminiignore to keep them out of context automatically.

Set a Mental Budget Per Task

Before starting a session, decide what the task is worth. Use /stats to check in periodically. If you are burning tokens on exploration, stop and narrow the scope.

Token Caching

For repeated sessions on the same project, Gemini CLI supports token caching to avoid re-sending the same context. This is configured automatically but works best when your GEMINI.md and project files are stable between sessions.

4. Security and Safety

Keep the API Key Out of the Repo

The most common mistake. Add to a global gitignore:

bash
# Add to ~/.gitignore_global
.env
.env.*
.gemini/

Apply:

bash
git config --global core.excludesfile ~/.gitignore_global

The .gemini/ folder contains local state. The project settings file .gemini/settings.json is safe to commit, but nothing else in that folder should be.

Never Store the API Key in Plain Text

Use your system's secret manager or at minimum a .env file that is gitignored:

bash
# .env (gitignored)
GEMINI_API_KEY=your-api-key

Load it in your shell:

bash
# ~/.zshrc
[ -f ~/.env.local ] && source ~/.env.local

Review Before You Allow

Gemini CLI operates as an agent — it proposes actions and asks for approval. Never approve an action you have not read. Slow down on:

  • Any file deletion or overwrite
  • Any git push or remote operation
  • Any shell command that writes outside the project directory
  • Any network call (curl, wget, external fetches)

Disable Shell Access by Default

The shell tool is the most powerful — and most dangerous — built-in. Exclude it unless the task explicitly requires it:

json
{
  "tools": {
    "exclude": [
      "run_shell_command"
    ]
  }
}

Re-enable only when needed for that specific session.

YOLO Mode

Gemini CLI has a --yolo flag that automatically approves all agent actions without prompting. Do not use this in a normal working session. It grants the agent unrestricted access to your file system, terminal, and any configured tools. Only use it in a fully isolated, throwaway environment where you are comfortable with unrestricted execution.

Rotate Keys If They Are Exposed

If the API key ends up in a commit, git log, or shared file:

  1. Go to aistudio.google.com/apikey
  2. Delete the exposed key immediately
  3. Generate a new one
  4. Update your local config

Do not rely on rewriting git history to fully remove it. Treat it as compromised the moment it is visible.

Control What Gemini Can Read

Use .geminiignore to prevent Gemini from reading sensitive files. Also configure respectGitIgnore so anything already excluded from git is also excluded from Gemini's tools:

json
{
  "context": {
    "fileFiltering": {
      "respectGitIgnore": true
    }
  }
}

Do Not Feed Gemini Sensitive Data

Gemini sends context to Google's servers to generate responses. Do not paste:

  • Passwords or secrets
  • Private keys or certificates
  • Customer PII
  • Internal authentication tokens
  • Confidential business data

If you need Gemini to work with a file that references secrets (like an .env example), redact the values before sharing.

Opt Out of Telemetry

By default, usage statistics may be collected. Disable explicitly in your global settings:

json
{
  "privacy": {
    "usageStatisticsEnabled": false
  },
  "telemetry": {
    "enabled": false
  }
}

5. Useful Commands

Session Commands

CommandWhat It Does
/helpList all available commands
/statsShow token usage for the current session
/memory showDisplay all loaded context from GEMINI.md files
/memory refreshReload context files without restarting
/memory add <text>Append text to your global ~/.gemini/GEMINI.md
/clearReset the conversation and start fresh
/quitExit the CLI

CLI Flags

bash
# Run a one-off task without entering a session
gemini -p "What does the function in src/auth.ts do?"

# Start with a specific model
gemini --model gemini-2.5-pro

# Print output only (non-interactive, useful for piping)
gemini --print "Summarise this file" < README.md

Useful Shell Aliases

Add to ~/.zshrc:

bash
# Gemini CLI shortcuts
alias g='gemini'
alias gask='gemini -p'

# Start a session in a specific project
gp() {
    cd "$1" && gemini
}

# Quick one-shot questions (non-interactive)
ask() {
    gemini -p "$*"
}

6. Usage Tips

  1. Write a good GEMINI.md: The two minutes it takes saves you from explaining the project every session.
  2. Exclude the shell tool by default: Most tasks — reviewing code, explaining logic, writing docs — do not need shell access. Add it only when the task requires it.
  3. Use /memory show to audit context: Before starting a long session, confirm Gemini has loaded only the context you intend.
  4. Compact before switching tasks: When moving from one problem to another, use /clear to avoid carrying irrelevant history.
  5. Check /stats early: Calibrate how fast context is growing in a new session.
  6. Keep GEMINI.md in version control: The team benefits from shared conventions and constraints.
  7. Use .geminiignore: It is the easiest way to keep irrelevant files out of context and costs down.
  8. Prefer OAuth for personal projects: The free tier is generous and avoids any billing risk.

Customisation

Adjust based on your workflow:

  • Tighten or loosen tools.exclude as you learn which tools are safe for your project
  • Add project-specific banned patterns to .geminiignore (migration files, infra configs, secrets directories)
  • Update GEMINI.md whenever a convention changes — it is living documentation
  • Set up a team GEMINI.md template for new projects to start from a sensible baseline
  • Use the global ~/.gemini/GEMINI.md for conventions that apply across all your work

Remember: The goal is intentional use, not restriction for its own sake.

  • Claude Code Setup — Setting up Anthropic's AI coding assistant alongside Gemini
  • CLI Setup — The shell environment your AI tools run inside