Tauri - Run bash Script - Example

1.1k Views Asked by At

I'm new to Tauri and Rust in general.

I'm working on this desktop app that will run different bash commands such as:

  • returning some outputs
  • open a new window (terminal) to run a process with output value

I'm not entirely sure how to best make it work.

Would somebody has snippet related to bash script in a tauri App ? To get a general idea ?
Something as small echo "hello" or anything else really or even opening an app with osascript.

Anything would be very much appreciated

tauri.conf.json

"tauri": {
"allowlist": {
  "all": false,
  "shell": {
    "all": true,
    "execute": true, 
    "sidecar": true,
    "open": true,
    "scope": [
      {
        "name": "test",
        "cmd": "echo",
        "args": ["hello"]
      },            
      {
        "name": "testing",
        "cmd": "osascript",
        "args": ["-e", "tell application \"Calendar\" to activate"]
      }
    ]
  }

main.js

const { Command } = window.__TAURI__.shell
async function greet() {
  console.log("call")
  new Command('test', ["hello"])
  new Command('testing', ["-e", "tell application \"Calendar\" to activate"])
}
2

There are 2 best solutions below

0
arnox On

I'm also new to this, and just figured it out. Try this:

tauri.config.json

"tauri": {
    "allowlist": {
      "all": true,
      "shell": {
        "all": true,
        "execute": true,
        "sidecar": true,
        "open": true,
        "scope": [
          {
            "name": "ls",
            "cmd": "ls",
            "args": [{ "validator": "\\S+" }] // pass arbitrary args from JS
          }
        ]
      },

In your js file:

import { Command } from '@tauri-apps/api/shell';
// 
// 'ls'   must match the command specified in tauri.config.json "shell" > "scope"
// '-laF' any parameters you want
// for more info on this, see: https://tauri.app/v1/api/js/shell/
//
const command = new Command('ls', '-laF');

command.on('close', data => {
  console.log(`command finished with code ${data.code} and signal ${data.signal}`);
});

command.on('error', error => console.error(`command error: "${error}"`));
command.stdout.on('data', line => console.log(`command stdout: "${line}"`));
command.stderr.on('data', line => console.log(`command stderr: "${line}"`));

const child = await command.execute();
0
Alex On

I also had issues with this trying to run npm and was getting an error of "program not found" - a solution for Windows at least was to add .cmd at the end of the command and then it started working.

{
"name": "npm",
  "cmd": "npm.cmd",
  "args": //
}