実行するディレクトリ(カレントディレクトリ)を指定する

Recipe ID: shell-005

コマンドを実行するディレクトリ(カレントディレクトリ / CWD)を指定する方法を解説します。
特定のディレクトリにあるスクリプトを実行したり、出力ファイルの保存先を制御する場合に必要です。

前提条件

プラグインのインストールが必要です。

npm run tauri add shell

Permissions (権限) の設定

src-tauri/capabilities/default.json に以下の権限を追加します。

{
  "permissions": [
    ...,
    "shell:allow-open",
    {
      "identifier": "shell:allow-execute",
      "allow": [
        {
          "name": "ls",
          "cmd": "ls",
          "args": true
        }
      ]
    }
  ]
}

1. フロントエンドから作成する (TypeScript)

Command.create() の第3引数以降(オプションオブジェクト)で指定できますが、API のバージョンによっては専用のメソッドが提供されている場合があります。
JavaScript の API では、インスタンス作成時は create(name, args, options) となり、options オブジェクトに cwd を指定します。

CWD を指定して実行

import { Command } from '@tauri-apps/plugin-shell';
import { tempDir } from '@tauri-apps/api/path';

async function listDirContent() {
  // 一時ディレクトリのパスを取得 (非同期)
  // または任意のパス '/tmp' など
  const targetDir = await tempDir();

  const cmd = Command.create('ls', [], {
    cwd: targetDir
  });
  
  const output = await cmd.execute();
  console.log('Result in target dir:', output.stdout);
}

2. バックエンドから作成する (Rust)

Command::current_dir() メソッドを使用します。

use std::process::Command;

#[tauri::command]
fn list_dir_content() -> Result<String, String> {
    let output = Command::new("ls")
        .current_dir("/tmp") // Unix向けディレクトリ
        .output()
        .map_err(|e| e.to_string())?;

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

cwd に指定するパスは、アクセス可能なパスである必要があります。
また、相対パスを指定した場合、アプリの実行位置(バイナリの場所)からの相対となるため、絶対パスでの指定を推奨します。@tauri-apps/api/path モジュールと組み合わせてパスを解決すると安全です。