Skip to content

run_shell_command 是 Gemini CLI 执行系统命令的核心工具。在 Windows 上用 powershell.exe,其他平台用 bash -c。开启 tools.shell.enableInteractiveShell 后支持交互式 TUI(vim、htop、git rebase -i)。用 tools.core 白名单和 tools.exclude 黑名单精确控制哪些命令可以执行;子进程会自动获得 GEMINI_CLI=1 环境变量用于检测。

Shell 工具参考(run_shell_command

run_shell_command 是 Gemini CLI 最强大也最需要谨慎使用的工具——它允许 AI 代理直接在系统上执行 Shell 命令。

基本参数

参数类型必填说明
commandstring要执行的完整 Shell 命令
descriptionstring展示给用户的操作描述
dir_pathstring命令执行目录(绝对路径或相对于工作区根目录)
is_backgroundboolean是否立即切为后台进程

返回值

工具返回 JSON 对象,包含:

字段说明
Command实际执行的命令字符串
Directory执行目录路径
Stdout标准输出内容
Stderr标准错误内容
Exit Code进程返回码
Background PIDs后台进程的 PID 列表

平台差异

平台执行方式
Windowspowershell.exe -NoProfile -Command
macOS / Linuxbash -c

交互式命令支持

默认情况下,Shell 工具使用 child_process,不支持交互式 TUI。开启交互式模式后,vimnanohtopgit rebase -i 等需要实时输入的程序都能正常运行。

在 settings.json 中开启

json
{
  "tools": {
    "shell": {
      "enableInteractiveShell": true,
      "showColor": true,
      "pager": "less"
    }
  }
}
配置项说明默认值
enableInteractiveShell使用 node-pty 支持交互式终端false
showColor保留 ANSI 颜色(仅 pty 模式有效)false
pager分页器程序"cat"
inactivityTimeout无输出等待超时(秒)系统默认

交互式命令使用方法:按 Tab 键聚焦到交互式终端,即可直接输入。

后台进程

is_background 设为 true,或命令末尾加 &,进程会立即切到后台执行,CLI 可继续响应用户输入。Background PIDs 字段会返回对应的进程 ID。

GEMINI_CLI 环境变量

run_shell_command 执行的所有命令都会自动获得 GEMINI_CLI=1 环境变量。脚本可以用它检测是否在 Gemini CLI 中运行:

bash
if [ "$GEMINI_CLI" = "1" ]; then
  echo "正在 Gemini CLI 中运行"
fi

命令权限控制

重要tools.core全部内置工具的白名单,不只是 Shell 命令。一旦设置了 tools.core,未列出的工具(read_filewrite_fileglob 等)都会被禁用。

白名单(只允许特定命令)

只允许 gitnpm 命令,禁止其他所有 Shell 命令:

json
{
  "tools": {
    "core": [
      "read_file",
      "write_file",
      "glob",
      "grep_search",
      "list_directory",
      "replace",
      "run_shell_command(git)",
      "run_shell_command(npm)"
    ]
  }
}

黑名单(禁止特定命令)

允许所有命令但禁止 rmtools.exclude 已被标记为废弃,建议改用 Policy Engine):

json
{
  "tools": {
    "core": ["run_shell_command"],
    "exclude": ["run_shell_command(rm)"]
  }
}

命令验证逻辑

  1. 链式命令拆分&&||; 连接的命令会逐个验证,任意一段被禁就整条拒绝
  2. 前缀匹配:允许 git 时,git statusgit log --oneline 都被允许
  3. 黑名单优先:同时在白名单和黑名单中的命令按黑名单处理

使用场景

  • 运行构建和测试npm run buildpytestgo test ./...
  • 版本控制操作git statusgit loggit diff
  • 安装依赖npm installpip install -r requirements.txt
  • 启动开发服务器npm run dev &(后台运行)
  • 系统信息查询df -hps aux

安全建议

在自动化场景(CI/CD、无头模式)中使用 Shell 工具时:

  1. 配合沙箱模式隔离命令执行环境
  2. tools.core 白名单限定允许的命令集合
  3. 敏感操作(文件删除、网络请求)保留用户确认流程

常见问题

Q: AI 执行命令时会弹确认框吗?

A: 默认会弹出确认对话框,显示命令内容和描述。可以在 /settings 中配置"自动批准"级别来减少弹窗。详见 settings.json 配置参考

Q: Windows 上能执行 bash 命令吗?

A: 可以,但需要 Git Bash 或 WSL。如果 Windows 上没有安装这些工具,建议在 WSL 环境中启动 Gemini CLI,或改用 PowerShell 等价命令。

Q: 命令执行超时怎么处理?

A: 可以用 is_background: true 让长时间命令切到后台,或调整 inactivityTimeout 配置项(需要 enableInteractiveShell: true)。