Appearance
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 命令。
基本参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
command | string | 是 | 要执行的完整 Shell 命令 |
description | string | 否 | 展示给用户的操作描述 |
dir_path | string | 否 | 命令执行目录(绝对路径或相对于工作区根目录) |
is_background | boolean | 否 | 是否立即切为后台进程 |
返回值
工具返回 JSON 对象,包含:
| 字段 | 说明 |
|---|---|
Command | 实际执行的命令字符串 |
Directory | 执行目录路径 |
Stdout | 标准输出内容 |
Stderr | 标准错误内容 |
Exit Code | 进程返回码 |
Background PIDs | 后台进程的 PID 列表 |
平台差异
| 平台 | 执行方式 |
|---|---|
| Windows | powershell.exe -NoProfile -Command |
| macOS / Linux | bash -c |
交互式命令支持
默认情况下,Shell 工具使用 child_process,不支持交互式 TUI。开启交互式模式后,vim、nano、htop、git 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_file、write_file、glob等)都会被禁用。
白名单(只允许特定命令)
只允许 git 和 npm 命令,禁止其他所有 Shell 命令:
json
{
"tools": {
"core": [
"read_file",
"write_file",
"glob",
"grep_search",
"list_directory",
"replace",
"run_shell_command(git)",
"run_shell_command(npm)"
]
}
}黑名单(禁止特定命令)
允许所有命令但禁止 rm(tools.exclude 已被标记为废弃,建议改用 Policy Engine):
json
{
"tools": {
"core": ["run_shell_command"],
"exclude": ["run_shell_command(rm)"]
}
}命令验证逻辑
- 链式命令拆分:
&&、||、;连接的命令会逐个验证,任意一段被禁就整条拒绝 - 前缀匹配:允许
git时,git status、git log --oneline都被允许 - 黑名单优先:同时在白名单和黑名单中的命令按黑名单处理
使用场景
- 运行构建和测试:
npm run build、pytest、go test ./... - 版本控制操作:
git status、git log、git diff - 安装依赖:
npm install、pip install -r requirements.txt - 启动开发服务器:
npm run dev &(后台运行) - 系统信息查询:
df -h、ps aux
安全建议
在自动化场景(CI/CD、无头模式)中使用 Shell 工具时:
- 配合沙箱模式隔离命令执行环境
- 用
tools.core白名单限定允许的命令集合 - 敏感操作(文件删除、网络请求)保留用户确认流程
常见问题
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)。