Google ZX - shell scripts with Javascript

How to write shell-scripts with Javascript and Node.js

Tom • Typescript & Javascript, Tools & Development, Linux & OSS •

A truly universal language

With the rise of Node.js, Javascript (and recently, Typescript), has become a prominent language to write all sorts of different scripts. Thanks to the core libraries included with every Node.js-instance, developers have also access to various calls to the Operating System. The flexibility of Javascript (albeit with a cost of harder maintenance) combined with that powerful runtime-engine helped it gain a large footprint in current server environments. For UNIX machines, this means that Javascript lives alongside the well established Bash-scripts, which are supported natively by the Operating System.

But what if…

But what if you could directly call Bash-commands inside of your Node.js-scripts? You may want to use Javascript for most of the implementations, but have the requirement to use Bash here and there to accomplish a goal.

With one of Google’s latest projects, a CLI-tool simply called “zx”, such a library is now available. Best of all: you can use it right away. All you need is an installed Node.js instance that’s equal to or higher to version 14.

// Your JS-file. You can either use
// the .js-suffix or the alternative
// .mjs-suffix, which allows the global
// usage of 'await' when used with 'zx'.

// The nessary shebang, as in Bash-scripts
#!/usr/bin/env zx

// A simple demonstration on how to
// call Bash-command inside your JS.
// Here, we log the current working directory.
await $`echo $PWD`;

javascriptLanguageCheck out all coding posts

// Now to call your file, you can 
// simply use 'npx', the node package
// executor that comes with NPM.

npx zx ./demo.mjs

// For more examples, check out the 
// repo where Google provides some
// more real-world use cases.

By using the dollar-sign as an operator followed by two backticks that include you Bash-code, you can make actual calls as in a Bash-script.

And if you install "zx" as a global dependency, you can call your Javascript-files the same way as your Bash-scripts.

More to explore

This article only aims at giving an introduction into the package. For more information, check out the links in the addendum to fully explore the API and all the features “zx” supports.

Actions

Feedback

Suggested Posts