Write shell scripts in JavaScript with zx
Move a shell check to JavaScript with zx, keep paths with spaces intact, and handle grep’s no-match status without swallowing errors.
Your release script checks the notes for a TODO before the tag goes out. The notes file is named release notes.txt, and a missing file should stop the release. A short shell conditional can lose the difference between an unreadable file and one with nothing left to fix.
Keep the command’s three outcomes
This Bash check quotes the file argument correctly. The issue is the conditional. Both a no-match exit and a read error land in the else branch.
if grep -qF -- TODO "$1"; then
printf 'Release notes contain TODO\n'
else
printf 'Release notes ready\n'
fiPass missing.txt and you see a grep diagnostic followed by Release notes ready.
Grep uses exit status 0 for a match and 1 for no match. An error has a higher exit status. You can handle that in Bash. If the rest of the release script already uses JavaScript, keep the grep command and handle its result in the same language.
Pass the path as one argument
Install zx as a development dependency and save the check as check.mjs. The tagged template quotes the value of file for the shell. Keep -- so a filename beginning with a dash stays a filename.
import { $ } from "zx"
const file = process.argv[2] ?? "release notes.txt"
const result = await $({ quiet: true, nothrow: true })`grep -qF -- TODO ${file}`
if (result.exitCode === 0) {
console.error("Release notes contain TODO")
process.exitCode = 1
} else if (result.exitCode === 1) {
console.log("Release notes ready")
} else {
console.error(result.stderr.trim() || "Could not read release notes")
process.exitCode = 2
}Run the script with the notes path as its argument and a missing file now produces a diagnostic and exit status 2.
By default, zx rejects the awaited command on a nonzero exit. Apply nothrow to this grep call because you expect 1 on a clean file. Leave the default for a later command such as creating the tag, where a nonzero exit should stop the script.
Before wiring this into CI, run it on a clean file and a file containing TODO. Check for exit statuses 0 and 1 respectively. A missing file should exit with 2.