Deno nuggets: Run shell commands
This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.
Problem
How to run shell commands from Deno?
> cat someScript.sh
echo "Hello world to $1"
echo "Hello world to $2" >&2
The shell script someScript.sh logs first argument to stdout and second argument to stderr.
Solution
Imports
No imports are required.
Run a shell command
Here are the steps involved in running a shell command and optionally collecting the output/error:
- Use Deno.run to create a child process (pass shell command, it’s args, and the output treatment)
const p=await Deno.run({
cmd: ['./someScript.sh', 'STDOUT', 'STDERR'],
stdout: 'piped',
stderr: 'piped'
})
- Wait for child process to finish
await p.status()
- Collect the output/error
await p.output() //stdout
await p.stderrOutput() //stderr
Complete code
Here is a complete example. Note that the output of the shell command needs to be decoded into string (if needed) and trimmed (as it usually contains extra line breaks at the end).
const td=(d:Uint8Array)=>new TextDecoder().decode(d);
const p=await Deno.run({
cmd: ['./someScript.sh', 'STDOUT', 'STDERR'],
stdout: 'piped',
stderr: 'piped'
});console.log(await p.status());
console.log('STDOUT:', td(await p.output()).trim());
console.log('STDERR:', td(await p.stderrOutput()).trim());
Here is the output of a sample run:
> deno run --allow-run app.ts
{ success: true, code: 0 }
STDOUT: Hello world to STDOUT
STDERR: Hello world to STDERR