Google ZX Scripting
Use this skill when writing scripts with Google's zx library — the tool that makes shell scripting with JavaScript/TypeScript productive and safe. Read only the reference file(s) needed for the task.
Quick Start
All zx scripts use the lite entry point for portability. Scripts are standalone .mjs files — no project setup required.
#!/usr/bin/env npx zx
import { $, fs, path, glob, chalk } from 'zx/core';
const files = await glob('src/**/*.ts');
await $`eslint ${files}`;
Run directly:
chmod +x script.mjs && ./script.mjs
# or
npx zx script.mjs
Critical Rules
- Always use
zx/core — never bare zx. Avoids the heavy CLI wrapper.
- Template literals auto-escape —
$`echo ${userInput}` is safe. Never manually quote interpolated variables.
- Arrays expand correctly —
$`cmd ${arrayOfArgs}` expands each element as a separate quoted argument.
- Non-zero exits throw — use
.nothrow() to suppress when you expect failures (e.g., grep with no matches).
within() for isolation — creates an async scope with its own $.cwd and $.env. Essential for parallel tasks.
- Pipe with
.pipe() — use $`cmd1`.pipe($`cmd2`) instead of shell |.
- Prefer zx builtins —
glob() over find, fs over cat/cp/mv, fetch() over curl.
cd() is global — use within() or $({cwd: '/path'}) for scoped directory changes.
- Scripts must be
.mjs — for top-level await support without bundler config.
Reference Map
| Need |
File |
$, ProcessPromise, ProcessOutput, configuration, piping, streams |
references/core-api.md |
| Ad-hoc scripts, CLI tools, build scripts, deployment, project scaffolding |
references/scripting-patterns.md |
| File processing, data pipelines, batch ops, AI scripts, log analysis |
references/processing-recipes.md |
Task Routing
- Writing a quick one-off command or shell automation ->
references/scripting-patterns.md
- Building a build/deploy/CI script ->
references/scripting-patterns.md
- Processing files, data, logs, or batch operations ->
references/processing-recipes.md
- Need API details for
$, pipes, streams, config -> references/core-api.md
- Combining multiple patterns (e.g., build + process) -> read both relevant files
Import Cheatsheet
// Core — always start here
import { $, fs, path, glob, chalk } from 'zx/core';
// Additional utilities (import individually as needed)
import { spinner, retry, question, echo, sleep, within,
stdin, tmpdir, tmpfile, which, ps, kill,
quote, YAML, argv, fetch } from 'zx/core';
Validation Checkpoints
Before executing destructive or bulk operations, always verify scope:
// Verify glob matches before bulk processing
const files = await glob('src/**/*.ts');
console.log(`Found ${files.length} files`);
if (files.length === 0) throw new Error('No files matched — check glob pattern');
if (files.length > 500) throw new Error(`Too many files (${files.length}) — narrow the glob`);
// Dry-run flag for destructive operations
const dryRun = argv['dry-run'] ?? false;
for (const file of files) {
if (dryRun) { console.log(`[dry-run] would delete ${file}`); continue; }
await fs.rm(file);
}
For parallel operations, use Promise.allSettled() to handle partial failures:
const results = await Promise.allSettled(
files.map(f => within(async () => $`process ${f}`))
);
const failed = results.filter(r => r.status === 'rejected');
if (failed.length > 0) {
console.error(chalk.red(`${failed.length}/${results.length} tasks failed`));
failed.forEach(r => console.error(r.reason));
process.exitCode = 1;
}
Conventions for Generated Scripts
- Shebang line: Always include
#!/usr/bin/env npx zx as the first line
- Verbose off: Set
$.verbose = false before main logic to suppress command echoing
- Error handling: Use the
main().catch() pattern — wrap logic in async function main(), then call main().catch(err => { console.error(chalk.red(err.message)); process.exit(1); })
- Output colors: Use
chalk.green() for success, chalk.red() for errors, chalk.yellow() for warnings, chalk.dim() for secondary info
- Progress: Use
spinner() for long-running operations in interactive contexts
- Arguments: Use
argv (pre-parsed minimist) for CLI argument handling
- Temp files: Use
tmpdir() and tmpfile() — they auto-clean on exit
- Parallelism: Use
Promise.all() with within() for parallel operations that need isolation
1---2name: google-zx-scripting3description: "Writes and executes JavaScript-based shell scripts using Google's zx library. Use when writing shell scripts, automation, build tools, file processing, CLI tools, deployment scripts, data pipelines, or batch operations. Also covers piping, streams, parallel execution, retries, cross-platform scripting, built-in fs utilities, and minimist argument parsing."4metadata:5 source: https://skillmd.com/skills/damusix/google-zx-scripting6---78# Google ZX Scripting91011Use this skill when writing scripts with Google's `zx` library — the tool that makes shell scripting with JavaScript/TypeScript productive and safe. Read only the reference file(s) needed for the task.1213## Quick Start1415All zx scripts use the **lite** entry point for portability. Scripts are standalone `.mjs` files — no project setup required.1617 #!/usr/bin/env npx zx1819 import { $, fs, path, glob, chalk } from 'zx/core';2021 const files = await glob('src/**/*.ts');22 await $`eslint ${files}`;2324Run directly:2526 chmod +x script.mjs && ./script.mjs27 # or28 npx zx script.mjs2930## Critical Rules31321. **Always use `zx/core`** — never bare `zx`. Avoids the heavy CLI wrapper.332. **Template literals auto-escape** — `` $`echo ${userInput}` `` is safe. Never manually quote interpolated variables.343. **Arrays expand correctly** — `` $`cmd ${arrayOfArgs}` `` expands each element as a separate quoted argument.354. **Non-zero exits throw** — use `.nothrow()` to suppress when you expect failures (e.g., `grep` with no matches).365. **`within()` for isolation** — creates an async scope with its own `$.cwd` and `$.env`. Essential for parallel tasks.376. **Pipe with `.pipe()`** — use `` $`cmd1`.pipe($`cmd2`) `` instead of shell `|`.387. **Prefer zx builtins** — `glob()` over `find`, `fs` over `cat`/`cp`/`mv`, `fetch()` over `curl`.398. **`cd()` is global** — use `within()` or `$({cwd: '/path'})` for scoped directory changes.409. **Scripts must be `.mjs`** — for top-level `await` support without bundler config.4142## Reference Map4344| Need | File |45|------|------|46| `$`, ProcessPromise, ProcessOutput, configuration, piping, streams | `references/core-api.md` |47| Ad-hoc scripts, CLI tools, build scripts, deployment, project scaffolding | `references/scripting-patterns.md` |48| File processing, data pipelines, batch ops, AI scripts, log analysis | `references/processing-recipes.md` |4950## Task Routing5152- Writing a quick one-off command or shell automation -> `references/scripting-patterns.md`53- Building a build/deploy/CI script -> `references/scripting-patterns.md`54- Processing files, data, logs, or batch operations -> `references/processing-recipes.md`55- Need API details for `$`, pipes, streams, config -> `references/core-api.md`56- Combining multiple patterns (e.g., build + process) -> read both relevant files5758## Import Cheatsheet5960 // Core — always start here61 import { $, fs, path, glob, chalk } from 'zx/core';6263 // Additional utilities (import individually as needed)64 import { spinner, retry, question, echo, sleep, within,65 stdin, tmpdir, tmpfile, which, ps, kill,66 quote, YAML, argv, fetch } from 'zx/core';6768## Validation Checkpoints6970Before executing destructive or bulk operations, always verify scope:7172 // Verify glob matches before bulk processing73 const files = await glob('src/**/*.ts');74 console.log(`Found ${files.length} files`);75 if (files.length === 0) throw new Error('No files matched — check glob pattern');76 if (files.length > 500) throw new Error(`Too many files (${files.length}) — narrow the glob`);7778 // Dry-run flag for destructive operations79 const dryRun = argv['dry-run'] ?? false;80 for (const file of files) {81 if (dryRun) { console.log(`[dry-run] would delete ${file}`); continue; }82 await fs.rm(file);83 }8485For parallel operations, use `Promise.allSettled()` to handle partial failures:8687 const results = await Promise.allSettled(88 files.map(f => within(async () => $`process ${f}`))89 );90 const failed = results.filter(r => r.status === 'rejected');91 if (failed.length > 0) {92 console.error(chalk.red(`${failed.length}/${results.length} tasks failed`));93 failed.forEach(r => console.error(r.reason));94 process.exitCode = 1;95 }9697## Conventions for Generated Scripts98991. **Shebang line**: Always include `#!/usr/bin/env npx zx` as the first line1002. **Verbose off**: Set `$.verbose = false` before main logic to suppress command echoing1013. **Error handling**: Use the `main().catch()` pattern — wrap logic in `async function main()`, then call `main().catch(err => { console.error(chalk.red(err.message)); process.exit(1); })`1024. **Output colors**: Use `chalk.green()` for success, `chalk.red()` for errors, `chalk.yellow()` for warnings, `chalk.dim()` for secondary info1035. **Progress**: Use `spinner()` for long-running operations in interactive contexts1046. **Arguments**: Use `argv` (pre-parsed `minimist`) for CLI argument handling1057. **Temp files**: Use `tmpdir()` and `tmpfile()` — they auto-clean on exit1068. **Parallelism**: Use `Promise.all()` with `within()` for parallel operations that need isolation