Skip to content

无头模式

无头模式允许您通过命令行脚本和自动化工具以编程方式运行 Gemini CLI,而无需任何交互式 UI。这对于脚本编写、自动化、CI/CD 管道和构建 AI 驱动的工具非常理想。

概述

无头模式提供了 Gemini CLI 的无头接口,该接口:

  • 通过命令行参数或标准输入接受提示
  • 返回结构化输出(文本或 JSON)
  • 支持文件重定向和管道
  • 实现自动化和脚本工作流
  • 为错误处理提供一致的退出代码

基本用法

直接提示

使用 --prompt (或 -p) 标志以无头模式运行:

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

标准输入

通过终端将输入管道传输到 Gemini CLI:

bash
echo "解释这段代码" | gemini

结合文件输入

从文件中读取并使用 Gemini 进行处理:

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

输出格式

文本输出 (默认)

标准的、人类可读的输出:

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

响应格式:

法国的首都是巴黎。

JSON 输出

返回包括响应、统计信息和元数据在内的结构化数据。此格式非常适合程序化处理和自动化脚本。

响应模式

JSON 输出遵循以下高级结构:

json
{
  "response": "string", // 回答您提示的主要 AI 生成内容
  "stats": {
    // 使用指标和性能数据
    "models": {
      // 按模型划分的 API 和 token 使用统计信息
      "[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": {
    // 仅在发生错误时出现
    "type": "string", // 错误类型 (例如 "ApiError", "AuthError")
    "message": "string", // 人类可读的错误描述
    "code": "number" // 可选的错误代码
  }
}

示例用法

bash
gemini -p "法国的首都是哪里?" --output-format json

响应:

json
{
  "response": "法国的首都是巴黎。",
  "stats": {
    "models": {
      "gemini-2.5-pro": {
        "api": {
          "totalRequests": 2,
          "totalErrors": 0,
          "totalLatencyMs": 5053
        },
        "tokens": {
          "prompt": 24939,
          "candidates": 20,
          "total": 25113,
          "cached": 21263,
          "thoughts": 154,
          "tool": 0
        }
      },
      "gemini-2.5-flash": {
        "api": {
          "totalRequests": 1,
          "totalErrors": 0,
          "totalLatencyMs": 1879
        },
        "tokens": {
          "prompt": 8965,
          "candidates": 10,
          "total": 9033,
          "cached": 0,
          "thoughts": 30,
          "tool": 28
        }
      }
    },
    "tools": {
      "totalCalls": 1,
      "totalSuccess": 1,
      "totalFail": 0,
      "totalDurationMs": 1881,
      "totalDecisions": {
        "accept": 0,
        "reject": 0,
        "modify": 0,
        "auto_accept": 1
      },
      "byName": {
        "google_web_search": {
          "count": 1,
          "success": 1,
          "fail": 0,
          "durationMs": 1881,
          "decisions": {
            "accept": 0,
            "reject": 0,
            "modify": 0,
            "auto_accept": 1
          }
        }
      }
    },
    "files": {
      "totalLinesAdded": 0,
      "totalLinesRemoved": 0
    }
  }
}

文件重定向

将输出保存到文件或管道传输到其他命令:

bash
# 保存到文件
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指定输出格式(文本、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

有关所有可用配置选项、设置文件和环境变量的完整详细信息,请参阅配置指南

示例

代码审查

bash
cat src/auth.py | gemini -p "审查此身份验证代码是否存在安全问题" > security-review.txt

生成提交消息

bash
result=$(git diff --cached | gemini -p "为这些更改编写简洁的提交消息" --output-format json)
echo "$result" | jq -r '.response'

API 文档

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

批量代码分析

bash
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

代码审查

bash
result=$(git diff origin/main...HEAD | gemini -p "审查这些更改是否存在错误、安全问题和代码质量问题" --output-format json)
echo "$result" | jq -r '.response' > pr-review.json

日志分析

bash
grep "ERROR" /var/log/app.log | tail -20 | gemini -p "分析这些错误并提出根本原因和修复建议" > error-analysis.txt

发布说明生成

bash
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

模型和工具使用跟踪

bash
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 tool calls ($tools_used) used with models: $models_used" >> usage.log
echo "$result" | jq -r '.response' > schema-docs.md
echo "最近使用趋势:"
tail -5 usage.log

资源

基于 MIT 许可证发布