无界面模式(Headless Mode)

无界面模式允许你在没有交互式界面的情况下,通过命令行脚本或自动化工具调用 Gemini CLI,非常适合脚本化、自动化、CI/CD 流水线以及构建 AI 驱动工具。

概览

无界面模式提供纯命令行的 Gemini CLI 接口,具备以下特性:

  • 通过命令行参数或标准输入接受 Prompt;
  • 返回结构化输出(文本或 JSON);
  • 支持文件重定向与管道传输;
  • 方便融入自动化脚本与工作流;
  • 通过一致的退出码便于错误处理。

基础用法

直接传入 Prompt

使用 --prompt(或 -p)即可进入无界面模式:

gemini --prompt "什么是机器学习?"

标准输入(stdin)

通过管道向 Gemini CLI 传入内容:

echo "解释这段代码" | gemini

结合文件输入

从文件读取内容并交由 Gemini 处理:

cat README.md | gemini --prompt "请总结这份文档"

输出格式

文本输出(默认)

默认返回易读的文本:

gemini -p "法国的首都是哪里?"

输出示例:

法国的首都是巴黎。

JSON 输出

以结构化数据返回响应、统计信息与元数据,适合程序化解析与自动化脚本。

响应结构

JSON 的整体结构如下:

{
  "response": "string",
  "stats": {
    "models": {
      "[model-name]": {
        "api": {
          /* 请求次数、错误、延迟 */
        },
        "tokens": {
          /* prompt、response、cached、total 等指标 */
        }
      }
    },
    "tools": {
      "totalCalls": "number",
      "totalSuccess": "number",
      "totalFail": "number",
      "totalDurationMs": "number",
      "totalDecisions": {
        /* accept、reject、modify、auto_accept 计数 */
      },
      "byName": {
        /* 各工具的详细统计 */
      }
    },
    "files": {
      "totalLinesAdded": "number",
      "totalLinesRemoved": "number"
    }
  },
  "error": {
    /* 仅在出错时存在:错误消息、堆栈、建议等 */
  }
}

示例用法

result=$(gemini -p "概述 React 的核心特性" --output-format json)
cat <<'JSON'
$result
JSON

输出示例:

{
  "response": "React 是一个专注于构建用户界面的 JavaScript 库……",
  "stats": {
    "models": {
      "gemini-2.5-flash": {
        "api": {
          "requests": 1,
          "errors": 0,
          "avgLatencyMs": 1031
        },
        "tokens": {
          "prompt": 37,
          "response": 182,
          "cached": 0,
          "total": 219
        }
      }
    },
    "tools": {
      "totalCalls": 0,
      "totalSuccess": 0,
      "totalFail": 0,
      "totalDurationMs": 0,
      "totalDecisions": {
        "accept": 0,
        "reject": 0,
        "modify": 0,
        "auto_accept": 0
      }
    },
    "files": {
      "totalLinesAdded": 0,
      "totalLinesRemoved": 0
    }
  }
}

重定向与管道

可将输出写入文件或交给其他命令:

# 保存到文件
gemini -p "介绍一下 Docker" > docker-explanation.txt
gemini -p "介绍一下 Docker" --output-format json > docker-explanation.json

# 追加输出
gemini -p "补充更多细节" >> docker-explanation.txt

# 与其他命令组合
gemini -p "什么是 Kubernetes?" --output-format json | jq '.response'
gemini -p "说明一下微服务架构" | wc -w
gemini -p "列出常见的编程语言" | grep -i "python"

配置选项

常用命令行参数如下:

选项说明示例
--prompt, -p启用无界面模式gemini -p "查询内容"
--output-format指定输出格式(text/json)gemini -p "查询内容" --output-format json
--model, -m指定使用的 Gemini 模型gemini -p "查询内容" -m gemini-2.5-flash
--debug, -d打开调试模式gemini -p "查询内容" --debug
--all-files, -a将所有文件纳入上下文gemini -p "查询内容" --all-files
--include-directories额外包含指定目录gemini -p "查询内容" --include-directories src,docs
--yolo, -y自动批准所有操作gemini -p "查询内容" --yolo
--approval-mode设置审批模式gemini -p "查询内容" --approval-mode auto_edit

更多配置项、设置文件及环境变量说明,请参阅配置指南

使用示例

代码审查

cat src/auth.py | gemini -p "审查这段认证代码是否存在安全风险" > security-review.txt

生成提交信息

result=$(git diff --cached | gemini -p "为这些改动写一条精简的提交信息" --output-format json)
echo "$result" | jq -r '.response'

生成 API 文档

result=$(cat api/routes.js | gemini -p "根据这些路由生成一份 OpenAPI 规范" --output-format json)
echo "$result" | jq -r '.response' > openapi.json

批量代码分析

for file in src/*.py; do
    echo "正在分析 $file..."
    result=$(cat "$file" | gemini -p "找出潜在缺陷并给出改进建议" --output-format json)
    echo "$result" | jq -r '.response' > "reports/$(basename "$file").analysis"
    echo "已完成 $(basename "$file") 的分析" >> reports/progress.log
done

代码审查(PR 范围)

result=$(git diff origin/main...HEAD | gemini -p "检查这些改动是否存在缺陷、安全问题以及代码质量风险" --output-format json)
echo "$result" | jq -r '.response' > pr-review.json

日志分析

grep "ERROR" /var/log/app.log | tail -20 | gemini -p "分析这些错误并给出可能的根因与修复建议" > error-analysis.txt

生成发布说明

result=$(git log --oneline v1.0.0..HEAD | gemini -p "根据这些提交生成发布说明" --output-format json)
response=$(echo "$result" | jq -r '.response')
echo "$response"
echo "$response" >> CHANGELOG.md

追踪模型与工具使用情况

result=$(gemini -p "解释这份数据库结构" --include-directories db --output-format json)
total_tokens=$(echo "$result" | jq -r '.stats.models // {} | to_entries | map(.value.tokens.total) | add // 0')
models_used=$(echo "$result" | jq -r '.stats.models // {} | keys | join(", ") | if . == "" then "none" else . end')
tool_calls=$(echo "$result" | jq -r '.stats.tools.totalCalls // 0')
tools_used=$(echo "$result" | jq -r '.stats.tools.byName // {} | keys | join(", ") | if . == "" then "none" else . end')
echo "$(date): 使用 $total_tokens 个 tokens,调用工具 $tool_calls 次(${tools_used}),涉及模型:$models_used" >> usage.log
echo "$result" | jq -r '.response' > schema-docs.md
echo "最近的使用趋势:"
tail -5 usage.log

参考资料