Mac や Linux 環境において Bash シェルスクリプト (.sh) を実行する方法を解説します。
前提条件
プラグインのインストールが必要です。
npm run tauri add shell
Permissions (権限) の設定
src-tauri/capabilities/default.json に以下の権限を追加します。
{
"permissions": [
...,
"shell:allow-open",
{
"identifier": "shell:allow-execute",
"allow": [
{
"name": "sh",
"cmd": "sh",
"args": true
}
]
}
]
}
1. フロントエンドから作成する (TypeScript)
Windows での注意点
Windows では標準でsh や bash は使用できませんが、Git Bash などがインストールされ、PATH が通っている場合は sh コマンドが使用可能です。または WSL (wsl.exe) を経由する必要があります。
import { Command } from '@tauri-apps/plugin-shell';
async function runBashScript() {
const isWindows = navigator.userAgent.includes('Windows');
// Windows の場合は Git Bash の sh.exe が PATH にあると仮定、または wsl
// ここでは Mac/Linux または Git Bash 環境を想定
const scriptPath = isWindows ? 'C:/Scripts/myscript.sh' : '/usr/local/bin/myscript.sh';
const cmd = Command.create('sh', [scriptPath]);
try {
const output = await cmd.execute();
console.log(output.stdout);
} catch (e) {
console.error("Execution failed. On Windows, ensure Git Bash is in PATH.", e);
}
}
2. バックエンドから作成する (Rust)
std::process::Command で sh または bash を呼び出します。
use std::process::Command;
#[tauri::command]
fn run_bash_script() -> Result<String, String> {
let script_path = "/usr/local/bin/myscript.sh";
let output = Command::new("sh")
.arg(script_path)
.output()
.map_err(|e| e.to_string())?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).to_string())
} else {
Err(String::from_utf8_lossy(&output.stderr).to_string())
}
}
スクリプト自体を実行コマンドとして登録する場合
スクリプトに Shebang (#!/bin/bash) があり、実行権限がある場合は、スクリプト自体を Command として許可することも可能です。
{
"allow": [
{
"name": "myscript",
"cmd": "/path/to/myscript.sh"
}
]
}