In a previous section, I mentioned that Deno could be used to replace bash scripts. For it to do that, you need to be able to execute commands on the host computer. Luckily, Deno has an exec module that allows you to do just that. Two helpful methods from that module are exec and execSequence. The former runs a single command, and the latter a series of commands. Each command should be provided as a string. The methods return a Promise and thus should be awaited or have a .then chained on to it.

To run these files, you also need to provide the --allow-run flag. This flag allows subprocesses to be run, but be aware that these subprocesses are run outside the Deno sandbox and thus don't have the same safety precautions as other Deno commands. As long as you're vigilant in what you are doing, this should be fine, though. In that way it's just like a bash script.

Here's an example of a script and how to run it:

import { exec } from 'https://deno.land/x/exec/mod.ts';

console.log(await exec('cat hello-world.txt'));
$ deno run --allow-run exec-commands.ts
The contents print here { status: { code: 0, success: true }, output: "" }

Most commands that you can run in your terminal should be able to be run in the exec or execSequence methods. One example of a command that doesn't work, however, is cd, or changing directories. For that, you need to use the Deno.chdir method from the Deno namespace. The method takes an absolute path as a parameter and changes directories for the script.


I finished! On to the next chapter