← Cookbook Files and processes Intermediate · Pooka 0.5.0

Run a shell command

Ask another program a question, read what it printed, and notice when it is unhappy.

You will use

  • pooka/process: process.run(command, args)
  • Output, with status, stdout and stderr
  • Guards to treat a non-zero status as a failure

The whole program

src/main.pooka
module main

import pooka/int
import pooka/io
import pooka/process

otp_version() -> Result(String, String) {
  let script = "io:format(\"~s\", [erlang:system_info(otp_release)]), halt()."
  match process.run("erl", ["-noshell", "-eval", script]) {
    Ok(output) if output.status == 0 -> Ok(output.stdout)
    Ok(output) -> Error(
      "erl exited with status " + int.to_string(output.status)
    )
    Error(problem) -> Error(problem.message)
  }
}

main() {
  match otp_version() {
    Ok(version) -> {
      io.println("Erlang/OTP " + version)
      Nil
    }
    Error(reason) -> {
      io.eprintln("Could not ask Erlang: " + reason)
      Nil
    }
  }

  match process.run("erl", ["-noshell", "-eval", "halt(3)."]) {
    Ok(output) -> {
      io.println("halt(3) exits with " + int.to_string(output.status))
      Nil
    }
    Error(problem) -> {
      io.eprintln(problem.message)
      Nil
    }
  }

  match process.run("no-such-command", []) {
    Ok(_) -> Nil
    Error(problem) -> {
      io.println("no-such-command: " + problem.message)
      Nil
    }
  }
}

Run it

$ pooka run
Erlang/OTP 29
halt(3) exits with 3
no-such-command: command not found

How it works

  1. A command and its arguments. process.run("erl", ["-noshell", "-eval", script]) runs erl with those arguments. They are passed along as they are, never interpreted by a shell, so spaces, quotes and * arrive exactly as written.
  2. Two kinds of trouble. If the program cannot be started at all, you get Error(ProcessError). If it starts and fails, you get Ok(output) with a non-zero output.status.
  3. Decide what success means. The guard Ok(output) if output.status == 0 accepts only a clean exit; the next arm turns any other status into an error message.
  4. Output is text. stdout and stderr are strings, ready for string.trim and string.split.

Try next: process.run_in(command, args, folder) runs a command in another folder, and process.run_with_timeout gives up after a while.