Skip to content
Myr

bash.md

This file

Path

docs/bash.md

1,274 lines · 20.7 KiB · Markdown

Last changed by

Add documentation about nano-spawn (#1157)ehmickybefore adoptioneb3cfba

History of this file

Take it

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1–8why, one step back
1<picture>
2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 🔍 Differences with Bash and zx8

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 9–10why, one step back
9This page describes the differences between [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)), Execa, and [zx](https://github.com/google/zx). Execa intends to be more:
10- [Simple](#simplicity): minimalistic API, no [globals](#global-variables), no [binary](#main-binary), no builtin CLI utilities.

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 11–12why, one step back
11- [Cross-platform](#shell): [no shell](shell.md) is used, only JavaScript.
12- [Secure](#escaping): no shell injection.

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

line 13why, one step back
13- [Featureful](#simplicity): all Execa features are available ([text lines iteration](#iterate-over-output-lines), [advanced piping](#piping-stdout-to-another-command), [simple IPC](#ipc), [passing any input type](#pass-any-input-type), [returning any output type](#return-any-output-type), [transforms](#transforms), [web streams](#web-streams), [convert to Duplex stream](#convert-to-duplex-stream), [cleanup on exit](termination.md#current-process-exit), [graceful termination](#graceful-termination), [forceful termination](termination.md#forceful-termination), and [more](../readme.md#documentation)).

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 14–15why, one step back
14- [Easy to debug](#debugging): [verbose mode](#verbose-mode-single-command), [detailed errors](#detailed-errors), [messages and stack traces](#cancelation), stateless API.
15- [Performant](#performance)

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 16–18why, one step back
16
17## Flexibility18

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 19why, one step back
19Unlike shell languages like Bash, libraries like Execa and zx enable you to write scripts with a more featureful programming language (JavaScript). This allows complex logic (such as [parallel execution](#parallel-commands)) to be expressed easily. This also lets you use any Node.js package.

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 20–36why, one step back
20
21## Shell2223The main difference between Execa and zx is that Execa does not require any shell. Shell-specific keywords and features are [written in JavaScript](#variable-substitution) instead.2425This is more cross-platform. For example, your code works the same on Windows machines without Bash installed.2627Also, there is no shell syntax to remember: everything is just plain JavaScript.2829If you really need a shell though, the [`shell`](shell.md) option can be used.3031## Simplicity3233Execa's scripting API mostly consists of only two methods: [`` $`command` ``](shell.md) and [`$(options)`](execution.md#globalshared-options).3435[No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.36

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 37why, one step back
37Execa is a thin wrapper around the core Node.js [`child_process` module](https://nodejs.org/api/child_process.html). It lets you use any of its native features.

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 38–40why, one step back
38
39## Modularity40

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 41why, one step back
41zx includes many builtin utilities: [`fetch()`](#http-requests), [`question()`](#cli-prompts), [`sleep()`](#sleep), [`echo()`](#printing-to-stdout), [`stdin()`](#retrieve-stdin), [`retry()`](#retry-on-error), [`spinner()`](#cli-spinner), [`globby`](#globbing), [`chalk`](https://github.com/chalk/chalk), [`fs`](https://github.com/jprichardson/node-fs-extra), [`os`](https://nodejs.org/api/os.html), [`path`](https://nodejs.org/api/path.html), [`yaml`](https://github.com/eemeli/yaml), [`which`](https://github.com/npm/node-which), [`ps`](https://github.com/webpod/ps), [`tmpfile()`](#temporary-file), [`argv`](#cli-arguments), Markdown scripts, remote scripts.

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 42why, one step back
42

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 43why, one step back
43Execa does not include any utility: it focuses on being small and modular instead. [Any Node.js package](https://github.com/sindresorhus/awesome-nodejs#command-line-utilities) can be used in your scripts.

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 44–50why, one step back
44
45## Performance4647Spawning a shell for every command comes at a performance cost, which Execa avoids.4849## Debugging50

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 51why, one step back
51Subprocesses can be hard to debug, which is why Execa includes a [`verbose`](#verbose-mode-single-command) option. It includes [more information](debugging.md#full-mode) than zx: timestamps, command completion and duration, interleaved commands, IPC messages.

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 52why, one step back
52

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 53why, one step back
53Also, Execa's error messages and [properties](#detailed-errors) are very detailed to make it clear to determine why a subprocess failed. Error messages and stack traces can be set with [`subprocess.kill(error)`](termination.md#error-message-and-stack-trace).

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 54–82why, one step back
54
55Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.5657## Examples5859### Main binary6061```sh62# Bash63bash file.sh64```6566```js67// zx68zx file.js6970// or a shebang can be used:71// #!/usr/bin/env zx72```7374```js75// Execa scripts are just regular Node.js files76node file.js77```7879### Global variables8081```js82// zx

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 83why, one step back
83await $`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 84–89why, one step back
84```
8586```js87// Execa88import {$} from 'execa';89

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 90why, one step back
90await $`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 91–98why, one step back
91```
9293[More info.](execution.md)9495### Command execution9697```sh98# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 99why, one step back
99npm run build

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 100–103why, one step back
100```
101102```js103// zx

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 104why, one step back
104await $`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 105–108why, one step back
105```
106107```js108// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 109why, one step back
109await $`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 110–111why, one step back
110```
111

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 112–113why, one step back
112[More info.](execution.md)
113

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 114–222why, one step back
114### Multiline commands
115116```sh117# Bash118npm run build \119 --example-flag-one \120 --example-flag-two121```122123```js124// zx125await $`npm run build ${[126 '--example-flag-one',127 '--example-flag-two',128]}`;129```130131```js132// Execa133await $`npm run build134 --example-flag-one135 --example-flag-two`;136```137138[More info.](execution.md#multiple-lines)139140### Concatenation141142```sh143# Bash144tmpDirectory="/tmp"145mkdir "$tmpDirectory/filename"146```147148```js149// zx150const tmpDirectory = '/tmp'151await $`mkdir ${tmpDirectory}/filename`;152```153154```js155// Execa156const tmpDirectory = '/tmp'157await $`mkdir ${tmpDirectory}/filename`;158```159160[More info.](execution.md#concatenation)161162### Variable substitution163164```sh165# Bash166echo $LANG167```168169```js170// zx171await $`echo $LANG`;172```173174```js175// Execa176await $`echo ${process.env.LANG}`;177```178179[More info.](input.md#environment-variables)180181### Escaping182183```sh184# Bash185echo 'one two'186```187188```js189// zx190await $`echo ${'one two'}`;191```192193```js194// Execa195await $`echo ${'one two'}`;196```197198[More info.](escaping.md)199200### Escaping multiple arguments201202```sh203# Bash204echo 'one two' '$'205```206207```js208// zx209await $`echo ${['one two', '$']}`;210```211212```js213// Execa214await $`echo ${['one two', '$']}`;215```216217[More info.](execution.md#multiple-arguments)218219### Subcommands220221```sh222# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 223why, one step back
223echo "$(npm run build)"

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 224–227why, one step back
224```
225226```js227// zx

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

lines 228–229why, one step back
228const result = await $`npm run build`;
229await $`echo ${result}`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 230–233why, one step back
230```
231232```js233// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

lines 234–235why, one step back
234const result = await $`npm run build`;
235await $`echo ${result}`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 236–243why, one step back
236```
237238[More info.](execution.md#subcommands)239240### Serial commands241242```sh243# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 244why, one step back
244npm run build && npm run test

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 245–248why, one step back
245```
246247```js248// zx

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 249why, one step back
249await $`npm run build && npm run test`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 250–253why, one step back
250```
251252```js253// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

lines 254–255why, one step back
254await $`npm run build`;
255await $`npm run test`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 256–261why, one step back
256```
257258### Parallel commands259260```sh261# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

lines 262–263why, one step back
262npm run build &
263npm run test &

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 264–267why, one step back
264```
265266```js267// zx

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 268why, one step back
268await Promise.all([$`npm run build`, $`npm run test`]);

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 269–272why, one step back
269```
270271```js272// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 273why, one step back
273await Promise.all([$`npm run build`, $`npm run test`]);

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 274–280why, one step back
274```
275276### Global/shared options277278```sh279# Bash280options="timeout 5"

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

lines 281–283why, one step back
281$options npm run init
282$options npm run build283$options npm run test

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 284–287why, one step back
284```
285286```js287// zx

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 288–292why, one step back
288const $$ = $({verbose: true});
289290await $$`npm run init`;291await $$`npm run build`;292await $$`npm run test`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 293–298why, one step back
293```
294295```js296// Execa297import {$ as $_} from 'execa';298

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 299why, one step back
299const $ = $_({verbose: true});

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 300why, one step back
300

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

lines 301–303why, one step back
301await $`npm run init`;
302await $`npm run build`;303await $`npm run test`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 304–311why, one step back
304```
305306[More info.](execution.md#globalshared-options)307308### Environment variables309310```sh311# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 312why, one step back
312EXAMPLE=1 npm run build

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 313–316why, one step back
313```
314315```js316// zx

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 317why, one step back
317await $({env: {EXAMPLE: '1'}})`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 318–321why, one step back
318```
319320```js321// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 322why, one step back
322await $({env: {EXAMPLE: '1'}})`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 323–335why, one step back
323```
324325[More info.](input.md#environment-variables)326327### Local binaries328329```sh330# Bash331npx tsc --version332```333334```js335// zx

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 336why, one step back
336await $({preferLocal: true})`tsc --version`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 337–340why, one step back
337```
338339```js340// Execa

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 341why, one step back
341await $({preferLocal: true})`tsc --version`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 342–345why, one step back
342```
343344[More info.](environment.md#local-binaries)345

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 346why, one step back
346### Retrieve stdin

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 347why, one step back
347

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 348–352why, one step back
348```sh
349# Bash350read content351```352

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 353–364why, one step back
353```js
354// zx355const content = await stdin();356```357358```js359// Execa360import getStdin from 'get-stdin';361362const content = await getStdin();363```364

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 365–439why, one step back
365[More info.](https://github.com/sindresorhus/get-stdin)
366367### Pass input to stdin368369```sh370# Bash371cat <<<"example"372```373374```js375// zx376$({input: 'example'})`cat`;377```378379```js380// Execa381$({input: 'example'})`cat`;382```383384### Pass any input type385386```sh387# Bash only allows passing strings as input388```389390```js391// zx only allows passing specific input types392```393394```js395// Execa - main.js396const ipcInput = [397 {task: 'lint', ignore: /test\.js/},398 {task: 'copy', files: new Set(['main.js', 'index.js']),399}];400await $({ipcInput})`node build.js`;401```402403```js404// Execa - build.js405import {getOneMessage} from 'execa';406407const ipcInput = await getOneMessage();408```409410[More info.](ipc.md#send-an-initial-message)411412### Return any output type413414```sh415# Bash only allows returning strings as output416```417418```js419// zx only allows returning specific output types420```421422```js423// Execa - main.js424const {ipcOutput} = await $({ipc: true})`node build.js`;425console.log(ipcOutput[0]); // {kind: 'start', timestamp: date}426console.log(ipcOutput[1]); // {kind: 'stop', timestamp: date}427```428429```js430// Execa - build.js431import {sendMessage} from 'execa';432433await sendMessage({kind: 'start', timestamp: new Date()});434await runBuild();435await sendMessage({kind: 'stop', timestamp: new Date()});436```437438[More info.](ipc.md#retrieve-all-messages)439

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 440–456why, one step back
440### Printing to stdout
441442```sh443# Bash444echo example445```446447```js448// zx449echo`example`;450```451452```js453// Execa454console.log('example');455```456

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 457why, one step back
457### Silent stdout

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 458–460why, one step back
458
459```sh460# Bash

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 461why, one step back
461npm run build > /dev/null

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 462–465why, one step back
462```
463464```js465// zx

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 466why, one step back
466await $`npm run build`.quiet();

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 467–469why, one step back
467```
468469```js

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 470why, one step back
470// Execa does not print stdout by default

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 471why, one step back
471await $`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 472–473why, one step back
472```
473

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 474why, one step back
474### Binary output

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 475–476why, one step back
475
476```sh

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 477–495why, one step back
477# Bash usually requires redirecting binary output
478zip -r - input.txt > output.txt479```480481```js482// zx483const stdout = await $`zip -r - input.txt`.buffer();484```485486```js487// Execa488const {stdout} = await $({encoding: 'buffer'})`zip -r - input.txt`;489```490491[More info.](binary.md#binary-output)492493### Verbose mode (single command)494495```sh

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 496–497why, one step back
496# Bash
497set -v

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 498why, one step back
498npm run build

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 499why, one step back
499set +v

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 500–502why, one step back
500```
501502```js

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 503why, one step back
503// zx

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 504why, one step back
504await $`npm run build`.verbose();

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 505–508why, one step back
505```
506507```js508// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 509why, one step back
509await $({verbose: 'full'})`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 510–511why, one step back
510```
511

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 512why, one step back
512[More info.](debugging.md#verbose-mode)

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 513why, one step back
513

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 514–519why, one step back
514### Verbose mode (global)
515516```sh517# Bash518set -v519npm run build

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 520–522why, one step back
520```
521522```

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 523–525why, one step back
523// zx
524$ zx --verbose file.js525$ npm run build

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

lines 526–527why, one step back
526Building...
527Done.

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 528–534why, one step back
528```
529530```531$ NODE_DEBUG=execa node file.js532[19:49:00.360] [0] $ npm run build533[19:49:00.360] [0] Building...534[19:49:00.360] [0] Done.

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 535–537why, one step back
535[19:49:00.383] [0] √ (done in 23ms)
536```537

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 538why, one step back
538[More info.](debugging.md#global-mode)

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 539–548why, one step back
539
540### Piping stdout to another command541542```sh543# Bash544echo npm run build | sort | head -n2545```546547```js548// zx

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 549–551why, one step back
549await $`npm run build`
550 .pipe($`sort`)551 .pipe($`head -n2`);

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 552–566why, one step back
552```
553554```js555// Execa556await $`npm run build`557 .pipe`sort`558 .pipe`head -n2`;559```560561[More info.](pipe.md)562563### Piping stdout and stderr to another command564565```sh566# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 567why, one step back
567npm run build |& cat

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 568–571why, one step back
568```
569570```js571// zx

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 572why, one step back
572const subprocess = $`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 573why, one step back
573const cat = $`cat`;

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

lines 574–576why, one step back
574subprocess.pipe(cat);
575subprocess.stderr.pipe(cat.stdin);576await Promise.all([subprocess, cat]);

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 577–580why, one step back
577```
578579```js580// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 581why, one step back
581await $({all: true})`npm run build`

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 582–590why, one step back
582 .pipe({from: 'all'})`cat`;
583```584585[More info.](pipe.md#source-file-descriptor)586587### Piping stdout to a file588589```sh590# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 591why, one step back
591npm run build > output.txt

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 592–595why, one step back
592```
593594```js595// zx

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

lines 596–598why, one step back
596import {createWriteStream} from 'node:fs';
597598await $`npm run build`.pipe(createWriteStream('output.txt'));

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 599–602why, one step back
599```
600601```js602// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 603why, one step back
603await $({stdout: {file: 'output.txt'}})`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 604–607why, one step back
604```
605606[More info.](output.md#file-output)607

Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7

lines 608–633why, one step back
608### Piping interleaved stdout and stderr to a file
609610```sh611# Bash612npm run build &> output.txt613```614615```js616// zx617import {createWriteStream} from 'node:fs';618619const subprocess = $`npm run build`;620const fileStream = createWriteStream('output.txt');621subprocess.pipe(fileStream);622subprocess.stderr.pipe(fileStream);623await subprocess;624```625626```js627// Execa628const output = {file: 'output.txt'};629await $({stdout: output, stderr: output})`npm run build`;630```631632[More info.](output.md#file-output)633

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 634–637why, one step back
634### Piping stdin from a file
635636```sh637# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 638why, one step back
638cat < input.txt

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 639–654why, one step back
639```
640641```js642// zx643const cat = $`cat`;644fs.createReadStream('input.txt').pipe(cat.stdin);645await cat;646```647648```js649// Execa650await $({inputFile: 'input.txt'})`cat`;651```652653[More info.](input.md#file-input)654

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 655–766why, one step back
655### Web streams
656657```js658// zx does not support web streams659```660661```js662// Execa663const response = await fetch('https://example.com');664await $({stdin: response.body})`npm run build`;665```666667[More info.](streams.md#web-streams)668669### Convert to Duplex stream670671```js672// zx does not support converting subprocesses to streams673```674675```js676// Execa677import {pipeline} from 'node:stream/promises';678import {createReadStream, createWriteStream} from 'node:fs';679680await pipeline(681 createReadStream('./input.txt'),682 $`node ./transform.js`.duplex(),683 createWriteStream('./output.txt'),684);685```686687[More info.](streams.md#convert)688689### Handle pipeline errors690691```sh692# Bash693set -e694npm run crash | sort | head -n2695```696697```js698// zx699try {700 await $`npm run crash`701 .pipe($`sort`)702 .pipe($`head -n2`);703// This is never reached.704// The process crashes instead.705} catch (error) {706 console.error(error);707}708```709710```js711// Execa712try {713 await $`npm run build`714 .pipe`sort`715 .pipe`head -n2`;716} catch (error) {717 console.error(error);718}719```720721[More info.](pipe.md#errors)722723### Return all pipeline results724725```sh726# Bash only allows returning each command's exit code727npm run crash | sort | head -n2728# 1 0 0729echo "${PIPESTATUS[@]}"730```731732```js733// zx only returns the last command's result734```735736```js737// Execa738const destinationResult = await execa`npm run build`739 .pipe`head -n 2`;740console.log(destinationResult.stdout); // First 2 lines of `npm run build`741742const sourceResult = destinationResult.pipedFrom[0];743console.log(sourceResult.stdout); // Full output of `npm run build`744```745746[More info.](pipe.md#result)747748### Split output into lines749750```sh751# Bash752npm run build | IFS='\n' read -ra lines753```754755```js756// zx757const lines = await $`npm run build`.lines();758```759760```js761// Execa762const lines = await $({lines: true})`npm run build`;763```764765[More info.](lines.md#simple-splitting)766

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 767–780why, one step back
767### Iterate over output lines
768769```sh770# Bash771while read772do773 if [[ "$REPLY" == *ERROR* ]]774 then775 echo "$REPLY"776 fi777done < <(npm run build)778```779780```js

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 781–782why, one step back
781// zx does not allow easily iterating over output lines.
782// Also, the iteration does not handle subprocess errors.

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 783–795why, one step back
783```
784785```js786// Execa787for await (const line of $`npm run build`) {788 if (line.includes('ERROR')) {789 console.log(line);790 }791}792```793794[More info.](lines.md#progressive-splitting)795

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 796why, one step back
796### Detailed errors

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 797–805why, one step back
797
798```sh799# Bash communicates errors only through the exit code and stderr800timeout 1 sleep 2801echo $?802```803804```js805// zx

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 806–810why, one step back
806await $`sleep 2`.timeout('1ms');
807// Error:808// at file:///home/me/Desktop/example.js:6:12809// exit code: null810// signal: SIGTERM

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 811–814why, one step back
811```
812813```js814// Execa

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 815why, one step back
815await $({timeout: 1})`sleep 2`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 816–844why, one step back
816// ExecaError: Command timed out after 1 milliseconds: sleep 2
817// at file:///home/me/Desktop/example.js:2:20818// at ... {819// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',820// originalMessage: '',821// command: 'sleep 2',822// escapedCommand: 'sleep 2',823// cwd: '/path/to/cwd',824// durationMs: 19.95693,825// failed: true,826// timedOut: true,827// isCanceled: false,828// isTerminated: true,829// isMaxBuffer: false,830// signal: 'SIGTERM',831// signalDescription: 'Termination',832// stdout: '',833// stderr: '',834// stdio: [undefined, '', ''],835// pipedFrom: []836// }837```838839[More info.](errors.md)840841### Exit codes842843```sh844# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 845why, one step back
845npm run build

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 846–850why, one step back
846echo $?
847```848849```js850// zx

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 851why, one step back
851const {exitCode} = await $`npm run build`.nothrow();

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 852–855why, one step back
852```
853854```js855// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 856why, one step back
856const {exitCode} = await $({reject: false})`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 857–864why, one step back
857```
858859[More info.](errors.md#exit-code)860861### Timeouts862863```sh864# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 865why, one step back
865timeout 5 npm run build

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 866–869why, one step back
866```
867868```js869// zx

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 870why, one step back
870await $`npm run build`.timeout('5s');

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 871–874why, one step back
871```
872873```js874// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 875why, one step back
875await $({timeout: 5000})`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 876–905why, one step back
876```
877878[More info.](termination.md#timeout)879880### Current filename881882```sh883# Bash884echo "$(basename "$0")"885```886887```js888// zx889await $`echo ${__filename}`;890```891892```js893// Execa894await $`echo ${import.meta.filename}`;895```896897### Current directory898899```sh900# Bash901cd project902```903904```js905// zx

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 906why, one step back
906const $$ = $({cwd: 'project'});

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 907why, one step back
907

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 908–909why, one step back
908// Or:
909cd('project');

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 910–922why, one step back
910```
911912```js913// Execa914const $$ = $({cwd: 'project'});915```916917[More info.](environment.md#current-directory)918919### Background subprocess920921```sh922# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 923why, one step back
923npm run build &

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 924–926why, one step back
924```
925926```js

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 927–928why, one step back
927// zx
928await $({detached: true})`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 929–932why, one step back
929```
930931```js932// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 933why, one step back
933await $({detached: true})`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 934–949why, one step back
934```
935936[More info.](environment.md#background-subprocess)937938### IPC939940```sh941# Bash does not allow simple IPC942```943944```js945// zx does not allow simple IPC946```947948```js949// Execa

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

line 950why, one step back
950const subprocess = $({node: true})`script.js`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 951why, one step back
951

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

line 952why, one step back
952for await (const message of subprocess.getEachMessage()) {

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 953why, one step back
953 if (message === 'ping') {

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

line 954why, one step back
954 await subprocess.sendMessage('pong');

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 955–983why, one step back
955 }
956});957```958959[More info.](ipc.md)960961### Transforms962963```sh964# Bash does not allow transforms965```966967```js968// zx does not allow transforms969```970971```js972// Execa973const transform = function * (line) {974 if (!line.includes('secret')) {975 yield line;976 }977};978979await $({stdout: [transform, 'inherit']})`echo ${'This is a secret.'}`;980```981982[More info.](transform.md)983

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 984why, one step back
984### Signal termination

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 985–997why, one step back
985
986```sh987# Bash988kill $PID989```990991```js992// zx993subprocess.kill();994```995996```js997// Execa

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 998–1000why, one step back
998subprocess.kill();
9991000// Or with an error message and stack trace:

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 1001why, one step back
1001subprocess.kill(error);

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 1002why, one step back
1002```

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 1003why, one step back
1003

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 1004–1032why, one step back
1004[More info.](termination.md#signal-termination)
10051006### Default signal10071008```sh1009# Bash does not allow changing the default termination signal1010```10111012```js1013// zx only allows changing the signal used for timeouts1014const $$ = $({timeoutSignal: 'SIGINT'});1015```10161017```js1018// Execa1019const $ = $_({killSignal: 'SIGINT'});1020```10211022[More info.](termination.md#default-signal)10231024### Cancelation10251026```sh1027# Bash1028kill $PID1029```10301031```js1032// zx

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1033–1036why, one step back
1033const controller = new AbortController();
1034await $({signal: controller.signal})`node long-script.js`;1035```1036

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 1037–1042why, one step back
1037```js
1038// Execa1039const controller = new AbortController();1040await $({cancelSignal: controller.signal})`node long-script.js`;1041```1042

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 1043why, one step back
1043[More info.](termination.md#canceling)

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

lines 1044–1075why, one step back
1044
1045### Graceful termination10461047```sh1048# Bash1049trap cleanup SIGTERM1050```10511052```js1053// zx1054// This does not work on Windows1055process.on('SIGTERM', () => {1056 // ...1057});1058```10591060```js1061// Execa - main.js1062const controller = new AbortController();1063await $({1064 cancelSignal: controller.signal,1065 gracefulCancel: true,1066})`node build.js`;1067```10681069```js1070// Execa - build.js1071import {getCancelSignal} from 'execa';10721073const cancelSignal = await getCancelSignal();1074await fetch('https://example.com', {signal: cancelSignal});1075```

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1076–1083why, one step back
1076
1077### Interleaved output10781079```sh1080# Bash prints stdout and stderr interleaved1081```10821083```js

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 1084–1085why, one step back
1084// zx
1085const all = String(await $`node example.js`);

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1086–1088why, one step back
1086```
10871088```js

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

line 1089why, one step back
1089// Execa

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1090–1098why, one step back
1090const {all} = await $({all: true})`node example.js`;
1091```10921093[More info.](output.md#interleaved-output)10941095### PID10961097```sh1098# Bash

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 1099why, one step back
1099npm run build &

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1100–1108why, one step back
1100echo $!
1101```11021103```js1104// zx does not return `subprocess.pid`1105```11061107```js1108// Execa

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

line 1109why, one step back
1109const {pid} = $`npm run build`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1110–1112why, one step back
1110```
11111112[More info.](termination.md#inter-process-termination)

Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594

lines 1113–1268why, one step back
1113
1114### CLI arguments11151116```js1117// zx1118const {myCliFlag} = argv;1119```11201121```js1122// Execa1123import {parseArgs} from 'node:util';11241125const {myCliFlag} = parseArgs({strict: false}).values;1126```11271128[More info.](https://nodejs.org/api/util.html#utilparseargsconfig)11291130### CLI prompts11311132```sh1133# Bash1134read -p "Question? " answer1135```11361137```js1138// zx1139const answer = await question('Question? ');1140```11411142```js1143// Execa1144import input from '@inquirer/input';11451146const answer = await input({message: 'Question?'});1147```11481149[More info.](https://github.com/SBoudrias/Inquirer.js)11501151### CLI spinner11521153```sh1154# Bash does not provide with a builtin spinner1155```11561157```js1158// zx1159await spinner(() => $`node script.js`);1160```11611162```js1163// Execa1164import {oraPromise} from 'ora';11651166await oraPromise($`node script.js`);1167```11681169[More info.](https://github.com/sindresorhus/ora)11701171### Sleep11721173```sh1174# Bash1175sleep 51176```11771178```js1179// zx1180await sleep(5000);1181```11821183```js1184// Execa1185import {setTimeout} from 'node:timers/promises';11861187await setTimeout(5000);1188```11891190[More info.](https://nodejs.org/api/timers.html#timerspromisessettimeoutdelay-value-options)11911192### Globbing11931194```sh1195# Bash1196ls packages/*1197```11981199```js1200// zx1201const files = await glob(['packages/*']);1202```12031204```js1205// Execa1206import {glob} from 'node:fs/promises';12071208const files = await Array.fromAsync(glob('packages/*'));1209```12101211[More info.](https://nodejs.org/api/fs.html#fspromisesglobpattern-options)12121213### Temporary file12141215```js1216// zx1217const filePath = tmpfile();1218```12191220```js1221// Execa1222import tempfile from 'tempfile';12231224const filePath = tempfile();1225```12261227[More info.](https://github.com/sindresorhus/tempfile)12281229### HTTP requests12301231```sh1232# Bash1233curl https://github.com1234```12351236```js1237// zx1238await fetch('https://github.com');1239```12401241```js1242// Execa1243await fetch('https://github.com');1244```12451246[More info.](https://nodejs.org/api/globals.html#fetch)12471248### Retry on error12491250```js1251// zx1252await retry(1253 5,1254 () => $`curl -sSL https://sindresorhus.com/unicorn`,1255)1256```12571258```js1259// Execa1260import pRetry from 'p-retry';12611262await pRetry(1263 () => $`curl -sSL https://sindresorhus.com/unicorn`,1264 {retries: 5},1265);1266```12671268[More info.](https://github.com/sindresorhus/p-retry)

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1269–1271why, one step back
1269
1270<hr>1271

Add documentation about nano-spawn (#1157)ehmickybefore adoptioneb3cfba

line 1272why, one step back
1272[**Next**: 🐭 Small packages](small.md)\

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1273–1274why, one step back
1273[**Previous**: 📎 Windows](windows.md)\
1274[**Top**: Table of contents](../readme.md#documentation)