主题
Shell 工具(run_shell_command)
本文档描述了 Gemini CLI 的 run_shell_command 工具。
描述
使用 run_shell_command 与底层系统交互、运行脚本或执行命令行操作。run_shell_command 执行给定的 shell 命令,如果 tools.shell.enableInteractiveShell 设置为 true,还包括需要用户输入的交互式命令(例如 vim、git rebase -i)。
在 Windows 上,命令使用 powershell.exe -NoProfile -Command 执行(除非你明确将 ComSpec 指向另一个 shell)。在其他平台上,它们使用 bash -c 执行。
参数
run_shell_command 接受以下参数:
command(字符串,必需):要执行的确切 shell 命令。description(字符串,可选):命令目的的简要描述,将显示给用户。directory(字符串,可选):执行命令的目录(相对于项目根目录)。如果未提供,命令在项目根目录中运行。
如何在 Gemini CLI 中使用 run_shell_command
使用 run_shell_command 时,命令作为子进程执行。run_shell_command 可以使用 & 启动后台进程。该工具返回有关执行的详细信息,包括:
Command:执行的命令。Directory:运行命令的目录。Stdout:标准输出流的输出。Stderr:标准错误流的输出。Error:子进程报告的任何错误消息。Exit Code:命令的退出代码。Signal:如果命令被信号终止,则为信号编号。Background PIDs:启动的任何后台进程的 PID 列表。
用法:
run_shell_command(command="Your commands.", description="Your description of the command.", directory="Your execution directory.")run_shell_command 示例
列出当前目录中的文件:
run_shell_command(command="ls -la")在特定目录中运行脚本:
run_shell_command(command="./my_script.sh", directory="scripts", description="Run my custom script")启动后台服务器:
run_shell_command(command="npm run dev &", description="Start development server in background")配置
你可以通过修改 settings.json 文件或使用 Gemini CLI 中的 /settings 命令来配置 run_shell_command 工具的行为。
启用交互式命令
要启用交互式命令,你需要将 tools.shell.enableInteractiveShell 设置为 true。这将使用 node-pty 进行 shell 命令执行,允许交互式会话。
示例 settings.json:
json
{
"tools": {
"shell": {
"enableInteractiveShell": true
}
}
}在输出中显示颜色
要在 shell 输出中显示颜色,你需要将 tools.shell.showColor 设置为 true。注意:此设置仅在启用 tools.shell.enableInteractiveShell 时适用。
json
{
"tools": {
"shell": {
"showColor": true
}
}
}交互式命令
run_shell_command 工具现在通过集成伪终端(pty)支持交互式命令。这允许你运行需要实时用户输入的命令,如文本编辑器(vim、nano)、基于终端的 UI(htop)和交互式版本控制操作(git rebase -i)。
当交互式命令运行时,你可以从 Gemini CLI 向其发送输入。要聚焦到交互式 shell,按 ctrl+f。终端输出,包括复杂的 TUI,将正确渲染。
重要说明
- 安全性: 执行命令时要小心,特别是那些从用户输入构造的命令,以防止安全漏洞。
- 错误处理: 检查
Stderr、Error和Exit Code字段以确定命令是否成功执行。 - 后台进程: 当使用
&在后台运行命令时,工具将立即返回,进程将继续在后台运行。
环境变量
当 run_shell_command 执行命令时,它在子进程的环境中设置 GEMINI_CLI=1 环境变量。这允许脚本或工具检测它们是否从 Gemini CLI 内部运行。
命令限制
你可以通过在配置文件中使用 tools.core 和 tools.exclude 设置来限制 run_shell_command 工具可以执行的命令。
tools.core:要将run_shell_command限制为特定命令集,请以run_shell_command(<command>)格式向tools类别下的core列表添加条目。tools.exclude:要阻止特定命令,请以run_shell_command(<command>)格式向tools类别下的exclude列表添加条目。