Em português: Escrevendo shell scripts melhores usando o poder do Node com Google ZX.

Writing better shell scripts using the power of Node with Google ZX


Screenshot of Google ZX's Github page.

A few days ago I discovered ZX: a tool made by Google that lets you write complex shell scripts using Node.js.

You would ask me: why in the hell would I write shell scripts using Javascript? Let me tell you a story:

The super script

In the company I work for, setting up the development environment was a long, manual process.

There is a lot of repositories to clone, a lot of docker images to set up, a lot of directory navigation to install npm and composer dependencies, a lot of .env files to copy, databases to create, etc.

This year we created a command line program written entirely in shell script to automate this process. The results were right away amazing: a process that sometimes took days, now take an hour to complete.

But over time, things started to look far from perfect...

  • Only developers with intermediate to advanced knowledge of shell scripts were engaging in keeping the repository alive.
  • Modularity was basically non-existent: we had to import the variables and helpers in the global script.
  • It was getting hard to maintain concise and legible code.
  • It was hard to treat errors and handling exceptions.
  • The readability of the repository wasn't good in general.
  • It was hard to let the user choose a single step of the process (for example, cloning repositories or installing the npm dependencies for all of them)

Porting to Google ZX

I looked into ZX's Github docs and thought it was the perfect opportunity to change things around.

The set up was simple: install ZX globally using npm, create a .mjs file and then call the scripts from it (based on the instructions on github). To execute, I just ran zx file.mjs.

In a few minutes I had a few steps of the process ported, with a lot of benefits:

  • Easier to modularize functions and variables, increasing code reuse.
  • More legible and easy-to-understand code, specially for those with only basic knowledge of shell scripting.
  • More control of the scripts output.
  • Easier to treat errors and exceptions.
  • Easier to stylize text on the terminal (thanks to Chalk).

It was clear right away that it was the way to go: I ported the entire script in three days and I couldn't be happier with the results.

I can't show any code, but there's a few screenshots without any sensitive company info of the script running.

Believe me, I had a blast re-writing it.

Screenshot of the script running. There's a success message showing that all pre-requisites where accepted.

Screenshot of the script running. There's a success message saying the Docker prerequisite was not fullfil.

If you work with complex shell scripting, I definitely recommend checking Google ZX out.

Keep reading...