If you do scripts in bash, that already means you’re a nice person. But it also means that Google is thinking of you.
Indeed, this small company which one day will be known all over the world, I am sure, has posted on its Github a tool called ZX which allows you to write scripts much more simply and much more rapidly.
Built on NodeJS, ZX won’t lose anyone who is already familiar with JavaScript and Node.js. ZX has the particularity of facilitating the creation of child_process
and the management of outgoing messages (stdout and stderr).
Let’s take a hello world type example that will use the “ls” command to list the files in a directory and retrieve the output of this command.
We will first create a directory:
mkdir hello
cd hello
Then we will initialize a new project in the folder:
npm init --yes
Then, to install zx, you will have to go through npm like this:
npm install --save-dev zx
We will then create a script with the extension .mjs
nano hello.mjs
Here is the code… Basically, we initialize the shebang and then just use the command recovery functions as described in the documentation .
Thus, we import the $ (shell) function and pass the ls command to it. We get the output (stdout) of ls in the variable output and we display this variable.
#! /usr/bin/env node
import { $ } from "zx";
const output = (await $`ls`).stdout;
console.log(output);
ZX is a nice way to do bash scripting with NodeJS without too much hassle. You can even mix this with markdown docs to run the “code” content contained in an .md file.