Gemini CLI Cheatsheet - Google Terminal AI Agent Full Reference
Gemini CLI is Google open-source terminal AI agent (Apache 2.0) for developers who need very long context and want the model to edit code autonomously against their own models; its 2M-token window fits whole-repository refactoring and analysis. Long context, forkable self-hosting, and GEMINI.md project memory set it apart. This sheet covers install/auth, headless automation (-p -o json), and MCP/extensions.
Typical Use Case
For engineers putting Gemini CLI into daily development and automation pipelines. Six lines map to six situations: installation and authentication, run modes including the interactive TUI and headless -p, global flags, session slash commands, MCP and extension management, and the GEMINI.md project memory. The engineering practice that pays off most is writing build and test commands into GEMINI.md and using .geminiignore to keep secrets and large directories out of context, running automation with approval mode yolo plus JSON output, and using /compress and checkpoints to keep long tasks alive.
Install & Auth 6
npm install -g @google/gemini-cligemini --versiongeminigemini --auth-method=api-keyexport GEMINI_API_KEY="your-key"export GOOGLE_GENAI_USE_VERTEXAI=trueRun Modes 8
geminigemini "Refactor the user-auth module"gemini -p "Explain this function"gemini -i "Implement the cache first"gemini mcpgemini extensionsgemini skillsgemini gemmaGlobal Flags 15
gemini -m gemini-2.5-pro "task"gemini -y "Refactor the whole module"gemini --approval-mode plan "Explore architecture"gemini -w feat/logingemini -sgemini --skip-trustgemini --checkpointinggemini -r latestgemini --list-sessionsgemini --delete-session 2gemini --include-directories ../backend,../frontendgemini -o json "task"gemini -e context7gemini -lgemini --debugSession Slash Commands 14
/help/model/context/compress/clear/save/restore/yolo/mcp list/tools/init/memory list/memory refresh/quitMCP & Extensions 7
gemini mcp add <name> <url>gemini mcp remove <name>gemini mcp listgemini mcp enable <name>gemini mcp disable <name>gemini extensions install <name>gemini mcp add --url https://example.com/mcpGEMINI.md & Config 5
echo "Build: make build\nTest: go test ./..." > GEMINI.md@./docs/architecture.md!git statusecho ".env\nnode_modules/" > .geminiignorecat ~/.gemini/settings.jsonParameter matrix
| Parameter | Effect | Example |
|---|---|---|
npm install -g @google/gemini-cli | Pick the model for this run, such as gemini-2.5-pro for hard reasoning or Flash for cheap quick edits. | npm install -g @google/gemini-cli |
gemini --version | Choose how much the agent may do without asking: plan (read-only), auto_edit, yolo or default. | gemini --version |
gemini(首次运行) | Run inside a fresh git worktree so the agent edits never touch your current checkout. | gemini |
--auth-method=api-key | Run tool calls inside the configured sandbox (Docker or Podman) instead of directly on the host. | gemini --auth-method=api-key |
GEMINI_API_KEY | Headless mode: run one prompt, print the answer and exit, which is what CI calls. | export GEMINI_API_KEY="your-key" |
GOOGLE_GENAI_USE_VERTEXAI=true | Set the output format to text, json or stream-json so a script can consume the result. | export GOOGLE_GENAI_USE_VERTEXAI=true |
gemini "重构 user-auth 模块" | Continue a previous conversation, given latest or a session index. | gemini "重构 user-auth 模块" |
gemini -p "解释这个函数" | Snapshot files before each edit so /restore can undo an unwanted change set. | gemini -p "解释这个函数" |
gemini -i "先实现缓存" | Add directories outside the workspace root to the map the agent can read. | gemini -i "先实现缓存" |
gemini -m gemini-2.5-pro | Choose between browser OAuth login and API-key authentication. | gemini -m gemini-2.5-pro "任务" |
gemini -y | Reload GEMINI.md during a session so an edited project instruction takes effect without restarting. | gemini -y "重构整模块" |
--approval-mode plan | Print the current token usage for the conversation so you know how much room is left. | gemini --approval-mode plan "探索架构" |
gemini -w feat/login | 在独立 git worktree 中运行 | gemini -w feat/login |
gemini -s | 在配置沙箱(Docker/Podman)中执行工具调用 | gemini -s |
gemini --skip-trust | 本次会话信任当前工作区 | gemini --skip-trust |
gemini --checkpointing | 启用逐次编辑快照,可用 /restore 恢复 | gemini --checkpointing |
gemini -r latest | 恢复上一个会话(latest 或索引) | gemini -r latest |
gemini --list-sessions | 列出当前项目的会话后退出 | gemini --list-sessions |
gemini --delete-session 2 | 按索引删除会话 | gemini --delete-session 2 |
--include-directories | 把额外目录加入工作区映射 | gemini --include-directories ../backend,../frontend |
gemini -o json | 输出格式 text/json/stream-json | gemini -o json "任务" |
gemini -e context7 | 限制本会话加载的扩展集合 | gemini -e context7 |
gemini -l | 列出已安装扩展后退出 | gemini -l |
gemini --debug | 输出详细调试日志 | gemini --debug |
/help | 列出所有可用命令 | /help |
/model | 切换激活模型 | /model |
/context | 显示当前对话 token 用量 | /context |
/compress | 总结对话释放上下文 | /compress |
/clear / /save / /restore | 重置对话 / 保存检查点 / 恢复会话 | /save |
/yolo | 跳过所有确认提示(慎用) | /yolo |
/mcp list / /tools | 列出 MCP 服务器 / 可用工具 | /mcp list |
/init | 为项目生成 GEMINI.md | /init |
/memory list / /memory refresh | 查看已加载上下文 / 重载 GEMINI.md | /memory refresh |
gemini mcp add <name> <url> | 添加 MCP 服务器 | gemini mcp add --url https://example.com/mcp |
gemini mcp remove / enable / disable | 移除 / 启用 / 禁用 MCP 服务器 | gemini mcp disable <name> |
gemini mcp list | 列出 MCP 服务器 | gemini mcp list |
gemini extensions install <name> | 安装 CLI 扩展 | gemini extensions install <name> |
gemini skills | 管理 agent skills(安装/链接/列举) | gemini skills |
echo "构建: make build" > GEMINI.md | 写项目记忆,每次会话自动加载 | echo "构建: make build\n测试: go test ./..." > GEMINI.md |
@./docs/architecture.md | 在提示词中注入文件/目录内容 | @./docs/architecture.md 这个架构怎么实现的? |
!git status | 在会话内直接执行 shell 命令 | !git status |
.geminiignore | 让 agent 远离密钥与大目录 | echo ".env\nnode_modules/" > .geminiignore |
cat ~/.gemini/settings.json | 查看用户级配置(模型/MCP/工具权限) | cat ~/.gemini/settings.json |
Common pitfalls
SymptomThe agent edited files in the repository while you only wanted it to read the code.
CauseApproval mode was default or yolo, so every tool call was accepted without prompting.
FixRelaunch with --approval-mode plan for exploration, and add .geminiignore entries so the paths you never want touched are outside the map.
SymptomThe agent refuses to act or answers as if it cannot see the project files.
CauseThe session was started from a directory above the repository root, so the workspace map contains no source files.
Fixcd into the project root before launching, and use --include-directories when the relevant code sits in a sibling directory.
SymptomEdits are applied to a branch you did not want to touch, or uncommitted work conflicts with the run.
CauseThe worktree flag was not used and the agent committed or rewrote files in the active checkout.
FixStart the session with -w feat/name to get an isolated worktree, and keep uncommitted changes stashed before the run.
SymptomCI output cannot be parsed because the answer contains commentary around the JSON.
CauseThe output format defaults to text, so the model wraps its answer in prose.
FixPass -o json (or stream-json for incremental output) and parse the response field instead of scraping stdout.
SymptomA long conversation stops accepting new instructions and replies to a truncated history.
CauseThe conversation exceeded the context window, so the earliest turns were dropped.
FixRun /compress to summarise the history, /save to checkpoint it, and use -r latest to resume in a fresh session.
SymptomThe same instruction is obeyed over and over despite /compress, or an edit is reverted on the next turn.
CauseThe project rules in GEMINI.md were not reloaded, so the agent is working from the older instructions.
FixRun /memory refresh, or confirm with /memory list that the expected context files are actually loaded.
SymptomTool calls fail inside the sandbox with a permission error on an otherwise writable path.
CauseThe sandbox container maps only the workspace directory, so any other path resolves outside the sandbox.
FixAdd the needed directory with --include-directories, or drop -s for a run where direct host access is acceptable.
Symptom在 CI / 服务器上跑时报认证错误,本机交互登录却正常
Cause本机走的是浏览器 OAuth 凭据,而无头环境没有浏览器也没有凭据文件。
FixCI 场景改用 gemini --auth-method=api-key 并预先 export GEMINI_API_KEY;企业内可用 GOOGLE_GENAI_USE_VERTEXAI=true 走 Vertex AI。
Troubleshooting
1Confirm which model the session is actually using
gemini --version; gemini --auth-method=api-keyThe command shows the active model and lets you switch it without restarting the session.
2Read the verbose log when a tool call misbehaves
gemini --approval-mode plan "探索架构"Debug logging records each tool invocation and its result, which is where a denied permission or a bad path shows up.
3Check how much context the conversation has consumed
gemini -p "任务" -o json --approval-mode=yoloThe token figure tells you whether to compress or start a new session.
4See which context files the agent loaded
/context → /compress → /saveIf GEMINI.md is missing from the list, your project instructions were never picked up.
5Review the MCP servers available to the session
gemini mcp list; gemini -l; 会话内 /mcp list 与 /toolsA disabled or missing server explains why a tool the agent should have is unavailable.
6把项目约定固化进记忆文件
echo "构建: make build\n测试: go test ./..." > GEMINI.md; /memory refresh写入后用 /memory refresh 重载(或 /memory list 确认内容已加载)。之后每次会话都会自动读取这些命令,agent 不必每次都被重复告知。
7隔离危险操作与保留回滚路径
echo ".env\nnode_modules/" > .geminiignore; gemini -w feat/login --checkpointing.geminiignore 让 agent 远离密钥与大目录;-w 在独立 git worktree 中运行、--checkpointing 保留编辑快照,两者叠加后即便改动不理想也能完整回退。
Command Examples
Headless run with JSON output for scripts
gemini -p -o json "对比当前代码与最近一次 tag 的 API 差异"-p 非交互即跑即退,-o json 再配 --save 可把结果落盘,是 CI 自动化的常用组合。
Output
(模型只输出结构化 JSON 供下游脚本消费,例如新增/删除的接口清单与风险提示)
One-shot quick question
gemini "帮我解释这个函数的递归逻辑"与 -p 相比,无参数的非交互调用同样即跑即退,无需进入 TUI。
Output
(直接在当前终端返回回答后退出,适合查文档片段与做单次决策)
Bootstrap project memory
/init
echo "Build: make build\nTest: go test ./..." > GEMINI.md
/memory refreshGEMINI.md 每次会话自动加载,把项目约定沉淀其中可显著减少重复提示;敏感文件用 .geminiignore 排除。
Output
(/init 生成 GEMINI.md 骨架,补充构建/测试命令后 refresh 立刻生效,无需重启会话)
Common Pitfalls
- A 2M-long context loads fast, but first-pass latency grows as you stuff in many files — configure GEMINI.md and .geminiignore so node_modules, logs, and other bulk files stay out of context.
- -p headless runs exit immediately with no human to approve file edits and command execution; scope allowed actions in config rather than defaulting to full write access.
- GEMINI.md conventions are auto-followed every session, so editing it or dependencies changes future behavior; use .geminiignore to keep .env-style secrets out of memory files.
- Custom model endpoints may not support all native abilities (e.g., tools, long context); verify behavior consistency in a controlled repo before production.
Tips
- The personal Google account free tier is 1000 requests/day and it is open-source/forkable — the default choice for long-context (2M) and self-hosted use.
- For headless automation use `gemini -p -o json` with --approval-mode=yolo (preferred over the deprecated -y) for unattended tasks.
- Write build/test commands into GEMINI.md; Gemini auto-loads it each session — more stable than repeating prompts. Use .geminiignore to block .env etc.
- Past the 2M ceiling use /compress to keep going; use /save + /restore to preserve sessions across days.
FAQ
How do I run Gemini CLI headless in CI?
Use -p (--prompt) print mode: it runs the task, prints the result and exits instead of entering the TUI. Supply GEMINI_API_KEY in the environment rather than relying on a local login. For planning jobs add --approval-mode plan to stay read-only, so the agent cannot unexpectedly modify files or run commands on CI.
What is each --approval-mode value for?
plan is read-only and good for exploring an architecture before touching anything. default pauses for confirmation on sensitive actions, which suits day-to-day work. auto_edit permits file edits automatically but still confirms critical operations, and is the usual mode for coding. yolo approves everything and carries the most risk — keep it for disposable containers or one-off environments.
What if the conversation outgrows the context window?
Check /context to see current token usage, and when you approach the limit run /compress to summarize the conversation and continue — it can carry you past the 2M ceiling. To start completely fresh, /clear resets the conversation. When switching to an unrelated task, /clear is cleaner than continuing in the same thread, since leftover context skews the new result.
What do GEMINI.md and .geminiignore do?
GEMINI.md sits at the project root and is loaded automatically on every session, which is where you put conventions such as "build with make build, test with go test ./..." so the agent stops guessing. .geminiignore excludes files it should not read — .env and node_modules/ in particular — keeping secrets out of the context and large directories from slowing responses.
How can I keep Gemini CLI changes out of my current branch?
Use -w / --worktree with a branch name: it creates a fresh git worktree and runs there, isolating the agent's edits from your current working tree so your branch stays clean. Diff or merge when you are done. This is the safest approach for trying several approaches in parallel or for large agent-driven rewrites.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Aug 5, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us