简体   繁体   中英

Running bash script from Deno

Let's say I've got this super useful and advanced bash script:

#!/usr/bin/env bash

echo What is your name?
read name
echo What is your age?
read age

When I try to run it from Deno with a simple script like this:

const process = Deno.run({
  cmd: [`./bash.sh`],
  stdin: "piped",
  stdout: "piped",
});

const decoder = new TextDecoder();

const output = await process.output()
const parsed = decoder.decode(output);

console.log(parsed);

It returns nothing, but if I simplify the Deno script to the first line of the bash script it returns the output just fine

const process = Deno.run({
  cmd: [`echo`, `What is your name?`],
  stdin: "piped",
  stdout: "piped",
});

const decoder = new TextDecoder();

const output = await process.output()
const parsed = decoder.decode(output);

console.log(parsed);

Why is this? I'd assume since the start of the bash file and the single line command both start with echo it would return the same result twice

Version 1.5 of denoadded the prompt function which allows you to completely remove the need for shelling out to a different program and handling inter-process communication via stdin/stdout.

let name: string | null = null;
let age: string | null = null;

while (name === null) {
  name = prompt("What is your name?");
}

while (age === null) {
  age = prompt("What is your age?");
}

console.log(`you are ${name}, ${age}yo`);

Your code is telling Deno to set up the subprocess to expect piped stdin -- but never providing it any content on stdin, Consequently, it hangs in the very first read .

If we take that out (letting stdin be passed through from the parent process), and do in fact answer the two prompts on the parent process's stdin, everything works perfectly:

deno run --allow-run run-bash.js <<'EOF'
A Nony Mouse
3
EOF

...with run-bash.js containing:

const process = Deno.run({
  cmd: [`./bash.sh`],
  stdout: "piped",
});

const decoder = new TextDecoder();

const output = await process.output()
const parsed = decoder.decode(output);

console.log(parsed);

...and your bash.sh unchanged. output thus captures the two prompts ( What is your name? and What is your age? ), and forwards them to the javascript interpreter's stdout as-requested.

You have to call bash to call your script ( of course with --allow-run option ) like:

const process = Deno.run({
  cmd: ["bash","bash.sh"],
  stdin: "piped",
  stdout: "piped",
});

const decoder = new TextDecoder();

const output = await process.output()
const parsed = decoder.decode(output);

console.log(parsed);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM