Tauri新手求助:执行Bash脚本的代码示例及实现方案
Tauri执行Bash命令/终端操作解决方案
核心需求实现
1. 获取命令输出结果
你的当前代码仅创建了Command实例但未执行,以下是修正后的完整实现:
前端(main.js)
const { Command } = window.__TAURI__.shell; // 执行echo命令并获取输出 async function getEchoOutput() { try { // 调用预定义在scope中的test命令 const output = await Command.execute('test'); console.log('命令标准输出:', output.stdout); console.log('命令错误输出:', output.stderr); } catch (error) { console.error('命令执行失败:', error); } } // 执行osascript打开日历应用 async function openCalendarApp() { try { const output = await Command.execute('testing'); console.log('osascript执行状态:', output.code === 0 ? '成功' : '失败'); } catch (error) { console.error('打开日历失败:', error); } }
配置优化(tauri.conf.json)
遵循最小权限原则,无需开启shell.all: true,仅保留必要权限:
"tauri": { "allowlist": { "all": false, "shell": { "execute": true, "open": true, "scope": [ { "name": "test", "cmd": "echo", "args": ["hello"] }, { "name": "testing", "cmd": "osascript", "args": ["-e", "tell application \"Calendar\" to activate"] }, // 支持动态传参的echo命令(可选) { "name": "dynamic-echo", "cmd": "echo", "args": ["*"] } ] } } }
如果需要动态传递参数,比如执行echo "自定义内容",可调用:
const dynamicResult = await Command.execute('dynamic-echo', ['自定义内容']);
2. 打开新终端窗口运行进程
跨平台需要针对不同系统适配终端启动命令,以下是前端实现:
const { Command, os } = window.__TAURI__.shell; async function openNewTerminal() { // 要在新终端中运行的命令(read用于保持窗口不自动关闭) const targetCommand = 'echo "新终端内运行的命令" && read'; let terminalArgs; const platform = await os.platform(); switch (platform) { case 'darwin': // macOS terminalArgs = ['open', '-a', 'Terminal', '--args', '-e', targetCommand]; break; case 'linux': // Linux(以GNOME Terminal为例) terminalArgs = ['gnome-terminal', '--', 'bash', '-c', targetCommand]; break; case 'win32': // Windows terminalArgs = ['cmd.exe', '/c', `start cmd /k "${targetCommand.replace(/"/g, '\\"')}"`]; break; default: throw new Error('当前平台不支持'); } try { await Command.execute(...terminalArgs); } catch (error) { console.error('打开终端失败:', error); } }
关键注意事项
- 严格控制
shell.scope中的命令和参数,避免过度授权导致安全风险。 - 必须处理命令执行的错误分支,覆盖权限不足、命令不存在等场景。
- 跨平台终端命令存在差异,若需适配更多终端(如Linux的Konsole),需补充对应分支逻辑。
内容的提问来源于stack exchange,提问作者Clément Liscot
相关产品推荐
相关产品推荐

