What is zx
Here is an example script from the project’s readme:
Why should I care?
Bitrise has hundreds of workflow steps for the most common operations, but every project's needs are different. If you have to do something custom, we provide the Script step for you that lets you write Bash code to do the task. This is often used for CI-specific actions, such as:
- compressing and moving files to certain folders
- calling external commands
- making network requests and uploading files
How to set up your workflow
First, you need to install the correct version of Node.js on the build VM and install zx itself.
You can use our Node Version Manager step to set up Node.js version 14, which is the minimum required version for zx. Next, install zx globally using the NPM step or with a script step that runs npm install -g zx.
- Script content: This is the place for your code
- Execute with / runner binary: zx . This is the command we installed globally previously
- Script file path: $TMPDIR/zx_script.mjs . We define this explicitly because the file extension matters when Node.js executes our script.
Running the workflow, you can see that the setup only takes a few seconds and the script itself is executed instantly:
What zx gives you
There are a few functions that zx gives you that makes writing scripts easier (for the full list, check out the project docs):
$`command`: Executes a given external command and returns a Promise, so you can await it to get the output:
cd() changes the current working directory
fetch() is a wrapper around the node-fetch package that makes HTTP requests easy.
For the full API check out the project documentation.
Example: a simple Slack notification
Let's look at a real-world example in a few lines of code. We are going to create a script that sends a Slack notification if a build fails.
The script makes an HTTP POST request using the Slack API. We access a few environment variables using the process.env.ENV_VAR syntax:
- SLACK_TOKEN: we don't want to store the sensitive token in the workflow, so we created a secret on Bitrise that the script can read as an environment variable
- BITRISE_BUILD_URL: this variable is exposed by Bitrise at runtime
- BITRISE_BUILD_STATUS: this is also exposed by Bitrise. If its value is 0 then every previous step has been successful, so this script won't send a message.
Environment variables: Bitrise exposes a lot of useful environment variables during the build that will come in handy for writing scripts. Check out our docs for the full list of variables.
Faster iteration: Did you know you can run Bitrise workflows on your local machine with Bitrise CLI? This can help in writing and debugging scripts. You can iterate on your script faster locally than doing real builds on Bitrise.