Write Bash scripts with Zx: Import TypeScript

By XiaoXin
A Bit Randomly

Table of contents 1. Virtual machine basic configuration configure static IP set hostname set hosts install ssh 2. Ubuntu system settings disable swap Modify kernel parameters 3. Install contained 4. Install Kubernetes com... Read Build a K8s cluster on Ubuntu 22.04

Main Contents

Write Bash scripts with Zx: Import TypeScript

If we want to write shell scripts using zx in TypeScript, there are a few minor differences that we need to account for.

Note: The TypeScript compiler provides a large number of configuration options that allow us to tweak how it compiles our TypeScript code. With this in mind, the TypeScript configuration and code below are designed to work with most TypeScript versions.

First, install the dependencies needed to run the TypeScript code:

npm install --save-dev typescript ts-node

ts-nodeThe package provides a TypeScript execution engine that allows us to transpile and run TypeScript code.

A file needs to be created tsconfig.jsoncontaining the following configuration:

  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs"

Create a new script and name it hello-world-typescript.ts. First, add the shebang line to tell the OS kernel to use a ts-nodeprogram to run our script:

#! ./node_modules/.bin/ts-node

In order to use the keyword in our TypeScript code await, we need to wrap it in an Immediately Invoked Function Expression (IIFE), as the zx documentation suggests:

// hello-world-typescript.ts
import { $ } from "zx";
void (async function () {
  await $`ls`;

Then you need to make the script executable:

chmod u+x hello-world-typescript.ts

Run the script:


You can see the following output:

$ ls

Scripting with zx in TypeScript is similar to using JavaScript but requires some additional configuration and wrapping of our code.


Please Share This Article Thank You!

Parts of Tutorial write Bash Scripts with ZX Library
Write Bash scripts with Zx: Build project launcher P1

Now that we've learned the basics of shell scripting with Google's zx, we're going to use it to build a tool. This tool will automate a usually time-consuming process: bootstrapping the configuration of a new Node.js ...

Write Bash scripts with Zx: How to use

First, let's create a new project: mkdir zx-shell-scripts cd zx-shell-scripts npm init --yes Then install the zx library: npm install --save-dev zx Note: zx's documentation recommends installing the library globally with n...