bash.md
This file
Path
docs/bash.md
1,295 lines · 21.0 KiB · Markdown
Last changed by
Allow appending to files (#1166)ehmickybefore adoption94a75df
History of this fileTake it
The walk stopped after 200 commits: lines older than aca3db3 point at it.
Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 1–8why, one step back1<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 zx8Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 9–10why, one step back9This 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.Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 11–12why, one step back11- [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 back13- [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 back14- [Easy to debug](#debugging): [verbose mode](#verbose-mode-single-command), [detailed errors](#detailed-errors), [messages and stack traces](#cancelation), stateless API.15- [Performant](#performance)Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 16–18why, one step back1617## Flexibility18Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 19why, one step back19Unlike 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.Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 20–36why, one step back2021## 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.36Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 37why, one step back37Execa 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.Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 38–40why, one step back3839## Modularity40Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 41why, one step back41zx 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.Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
line 42why, one step back42Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 43why, one step back43Execa 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.Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 44–50why, one step back4445## Performance4647Spawning a shell for every command comes at a performance cost, which Execa avoids.4849## Debugging50Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 51why, one step back51Subprocesses 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.Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
line 52why, one step back52Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 53why, one step back53Also, 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).Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 54–82why, one step back5455Finally, 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// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 83why, one step back83await $`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 84–89why, one step back84```8586```js87// Execa88import {$} from 'execa';89Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
line 90why, one step back90await $`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 91–98why, one step back91```9293[More info.](execution.md)9495### Command execution9697```sh98# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 99why, one step back99npm run buildImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 100–103why, one step back100```101102```js103// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 104why, one step back104await $`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 105–108why, one step back105```106107```js108// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 109why, one step back109await $`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 110–111why, one step back110```111Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 112–113why, one step back112[More info.](execution.md)113Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 114–222why, one step back114### Multiline commands115116```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# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 223why, one step back223echo "$(npm run build)"Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 224–227why, one step back224```225226```js227// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 228–229why, one step back228const result = await $`npm run build`;229await $`echo ${result}`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 230–233why, one step back230```231232```js233// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 234–235why, one step back234const result = await $`npm run build`;235await $`echo ${result}`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 236–243why, one step back236```237238[More info.](execution.md#subcommands)239240### Serial commands241242```sh243# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 244why, one step back244npm run build && npm run testImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 245–248why, one step back245```246247```js248// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 249why, one step back249await $`npm run build && npm run test`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 250–253why, one step back250```251252```js253// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 254–255why, one step back254await $`npm run build`;255await $`npm run test`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 256–261why, one step back256```257258### Parallel commands259260```sh261# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 262–263why, one step back262npm run build &263npm run test &Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 264–267why, one step back264```265266```js267// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 268why, one step back268await Promise.all([$`npm run build`, $`npm run test`]);Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 269–272why, one step back269```270271```js272// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 273why, one step back273await Promise.all([$`npm run build`, $`npm run test`]);Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 274–280why, one step back274```275276### Global/shared options277278```sh279# Bash280options="timeout 5"Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 281–283why, one step back281$options npm run init282$options npm run build283$options npm run testImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 284–287why, one step back284```285286```js287// zxImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 288–292why, one step back288const $$ = $({verbose: true});289290await $$`npm run init`;291await $$`npm run build`;292await $$`npm run test`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 293–298why, one step back293```294295```js296// Execa297import {$ as $_} from 'execa';298Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 299why, one step back299const $ = $_({verbose: true});Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
line 300why, one step back300Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 301–303why, one step back301await $`npm run init`;302await $`npm run build`;303await $`npm run test`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 304–311why, one step back304```305306[More info.](execution.md#globalshared-options)307308### Environment variables309310```sh311# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 312why, one step back312EXAMPLE=1 npm run buildImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 313–316why, one step back313```314315```js316// zxImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 317why, one step back317await $({env: {EXAMPLE: '1'}})`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 318–321why, one step back318```319320```js321// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 322why, one step back322await $({env: {EXAMPLE: '1'}})`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 323–335why, one step back323```324325[More info.](input.md#environment-variables)326327### Local binaries328329```sh330# Bash331npx tsc --version332```333334```js335// zxImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 336why, one step back336await $({preferLocal: true})`tsc --version`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 337–340why, one step back337```338339```js340// ExecaImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 341why, one step back341await $({preferLocal: true})`tsc --version`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 342–345why, one step back342```343344[More info.](environment.md#local-binaries)345Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 346why, one step back346### Retrieve stdinImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
line 347why, one step back347Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 348–352why, one step back348```sh349# Bash350read content351```352Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 353–364why, one step back353```js354// zx355const content = await stdin();356```357358```js359// Execa360import getStdin from 'get-stdin';361362const content = await getStdin();363```364Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 365–439why, one step back365[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)439Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 440–456why, one step back440### Printing to stdout441442```sh443# Bash444echo example445```446447```js448// zx449echo`example`;450```451452```js453// Execa454console.log('example');455```456Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 457why, one step back457### Silent stdoutImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 458–460why, one step back458459```sh460# BashImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 461why, one step back461npm run build > /dev/nullImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 462–465why, one step back462```463464```js465// zxImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 466why, one step back466await $`npm run build`.quiet();Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 467–469why, one step back467```468469```jsImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 470why, one step back470// Execa does not print stdout by defaultImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 471why, one step back471await $`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 472–473why, one step back472```473Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 474why, one step back474### Binary outputImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 475–476why, one step back475476```shImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 477–495why, one step back477# Bash usually requires redirecting binary output478zip -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```shImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 496–497why, one step back496# Bash497set -vImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 498why, one step back498npm run buildImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 499why, one step back499set +vImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 500–502why, one step back500```501502```jsImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 503why, one step back503// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 504why, one step back504await $`npm run build`.verbose();Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 505–508why, one step back505```506507```js508// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 509why, one step back509await $({verbose: 'full'})`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 510–511why, one step back510```511Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 512why, one step back512[More info.](debugging.md#verbose-mode)Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
line 513why, one step back513Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 514–519why, one step back514### Verbose mode (global)515516```sh517# Bash518set -v519npm run buildImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 520–522why, one step back520```521522```Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 523–525why, one step back523// zx524$ zx --verbose file.js525$ npm run buildImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 526–527why, one step back526Building...527Done.Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 528–534why, one step back528```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.Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 535–537why, one step back535[19:49:00.383] [0] √ (done in 23ms)536```537Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 538why, one step back538[More info.](debugging.md#global-mode)Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 539–548why, one step back539540### Piping stdout to another command541542```sh543# Bash544echo npm run build | sort | head -n2545```546547```js548// zxImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 549–551why, one step back549await $`npm run build`550 .pipe($`sort`)551 .pipe($`head -n2`);Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 552–566why, one step back552```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# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 567why, one step back567npm run build |& catImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 568–571why, one step back568```569570```js571// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 572why, one step back572const subprocess = $`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
line 573why, one step back573const cat = $`cat`;Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 574–576why, one step back574subprocess.pipe(cat);575subprocess.stderr.pipe(cat.stdin);576await Promise.all([subprocess, cat]);Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 577–580why, one step back577```578579```js580// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 581why, one step back581await $({all: true})`npm run build`Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 582–590why, one step back582 .pipe({from: 'all'})`cat`;583```584585[More info.](pipe.md#source-file-descriptor)586587### Piping stdout to a file588589```sh590# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 591why, one step back591npm run build > output.txtImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 592–595why, one step back592```593594```js595// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 596–598why, one step back596import {createWriteStream} from 'node:fs';597598await $`npm run build`.pipe(createWriteStream('output.txt'));Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 599–602why, one step back599```600601```js602// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 603why, one step back603await $({stdout: {file: 'output.txt'}})`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 604–607why, one step back604```605606[More info.](output.md#file-output)607Allow appending to files (#1166)ehmickybefore adoption94a75df
lines 608–628why, one step back608### Append stdout to a file609610```sh611# Bash612npm run build >> output.txt613```614615```js616// zx617import {createWriteStream} from 'node:fs';618619await $`npm run build`.pipe(createWriteStream('output.txt', {flags: 'a'}));620```621622```js623// Execa624await $({stdout: {file: 'output.txt', append: true}})`npm run build`;625```626627[More info.](output.md#file-output)628Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
lines 629–654why, one step back629### Piping interleaved stdout and stderr to a file630631```sh632# Bash633npm run build &> output.txt634```635636```js637// zx638import {createWriteStream} from 'node:fs';639640const subprocess = $`npm run build`;641const fileStream = createWriteStream('output.txt');642subprocess.pipe(fileStream);643subprocess.stderr.pipe(fileStream);644await subprocess;645```646647```js648// Execa649const output = {file: 'output.txt'};650await $({stdout: output, stderr: output})`npm run build`;651```652653[More info.](output.md#file-output)654Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 655–658why, one step back655### Piping stdin from a file656657```sh658# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 659why, one step back659cat < input.txtImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 660–675why, one step back660```661662```js663// zx664const cat = $`cat`;665fs.createReadStream('input.txt').pipe(cat.stdin);666await cat;667```668669```js670// Execa671await $({inputFile: 'input.txt'})`cat`;672```673674[More info.](input.md#file-input)675Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 676–787why, one step back676### Web streams677678```js679// zx does not support web streams680```681682```js683// Execa684const response = await fetch('https://example.com');685await $({stdin: response.body})`npm run build`;686```687688[More info.](streams.md#web-streams)689690### Convert to Duplex stream691692```js693// zx does not support converting subprocesses to streams694```695696```js697// Execa698import {pipeline} from 'node:stream/promises';699import {createReadStream, createWriteStream} from 'node:fs';700701await pipeline(702 createReadStream('./input.txt'),703 $`node ./transform.js`.duplex(),704 createWriteStream('./output.txt'),705);706```707708[More info.](streams.md#convert)709710### Handle pipeline errors711712```sh713# Bash714set -e715npm run crash | sort | head -n2716```717718```js719// zx720try {721 await $`npm run crash`722 .pipe($`sort`)723 .pipe($`head -n2`);724// This is never reached.725// The process crashes instead.726} catch (error) {727 console.error(error);728}729```730731```js732// Execa733try {734 await $`npm run build`735 .pipe`sort`736 .pipe`head -n2`;737} catch (error) {738 console.error(error);739}740```741742[More info.](pipe.md#errors)743744### Return all pipeline results745746```sh747# Bash only allows returning each command's exit code748npm run crash | sort | head -n2749# 1 0 0750echo "${PIPESTATUS[@]}"751```752753```js754// zx only returns the last command's result755```756757```js758// Execa759const destinationResult = await execa`npm run build`760 .pipe`head -n 2`;761console.log(destinationResult.stdout); // First 2 lines of `npm run build`762763const sourceResult = destinationResult.pipedFrom[0];764console.log(sourceResult.stdout); // Full output of `npm run build`765```766767[More info.](pipe.md#result)768769### Split output into lines770771```sh772# Bash773npm run build | IFS='\n' read -ra lines774```775776```js777// zx778const lines = await $`npm run build`.lines();779```780781```js782// Execa783const lines = await $({lines: true})`npm run build`;784```785786[More info.](lines.md#simple-splitting)787Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 788–801why, one step back788### Iterate over output lines789790```sh791# Bash792while read793do794 if [[ "$REPLY" == *ERROR* ]]795 then796 echo "$REPLY"797 fi798done < <(npm run build)799```800801```jsImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 802–803why, one step back802// zx does not allow easily iterating over output lines.803// Also, the iteration does not handle subprocess errors.Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 804–816why, one step back804```805806```js807// Execa808for await (const line of $`npm run build`) {809 if (line.includes('ERROR')) {810 console.log(line);811 }812}813```814815[More info.](lines.md#progressive-splitting)816Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 817why, one step back817### Detailed errorsImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 818–826why, one step back818819```sh820# Bash communicates errors only through the exit code and stderr821timeout 1 sleep 2822echo $?823```824825```js826// zxImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 827–831why, one step back827await $`sleep 2`.timeout('1ms');828// Error:829// at file:///home/me/Desktop/example.js:6:12830// exit code: null831// signal: SIGTERMImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 832–835why, one step back832```833834```js835// ExecaImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 836why, one step back836await $({timeout: 1})`sleep 2`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 837–865why, one step back837// ExecaError: Command timed out after 1 milliseconds: sleep 2838// at file:///home/me/Desktop/example.js:2:20839// at ... {840// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',841// originalMessage: '',842// command: 'sleep 2',843// escapedCommand: 'sleep 2',844// cwd: '/path/to/cwd',845// durationMs: 19.95693,846// failed: true,847// timedOut: true,848// isCanceled: false,849// isTerminated: true,850// isMaxBuffer: false,851// signal: 'SIGTERM',852// signalDescription: 'Termination',853// stdout: '',854// stderr: '',855// stdio: [undefined, '', ''],856// pipedFrom: []857// }858```859860[More info.](errors.md)861862### Exit codes863864```sh865# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 866why, one step back866npm run buildImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 867–871why, one step back867echo $?868```869870```js871// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 872why, one step back872const {exitCode} = await $`npm run build`.nothrow();Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 873–876why, one step back873```874875```js876// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 877why, one step back877const {exitCode} = await $({reject: false})`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 878–885why, one step back878```879880[More info.](errors.md#exit-code)881882### Timeouts883884```sh885# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 886why, one step back886timeout 5 npm run buildImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 887–890why, one step back887```888889```js890// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 891why, one step back891await $`npm run build`.timeout('5s');Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 892–895why, one step back892```893894```js895// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 896why, one step back896await $({timeout: 5000})`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 897–926why, one step back897```898899[More info.](termination.md#timeout)900901### Current filename902903```sh904# Bash905echo "$(basename "$0")"906```907908```js909// zx910await $`echo ${__filename}`;911```912913```js914// Execa915await $`echo ${import.meta.filename}`;916```917918### Current directory919920```sh921# Bash922cd project923```924925```js926// zxImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 927why, one step back927const $$ = $({cwd: 'project'});Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
line 928why, one step back928Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 929–930why, one step back929// Or:930cd('project');Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 931–943why, one step back931```932933```js934// Execa935const $$ = $({cwd: 'project'});936```937938[More info.](environment.md#current-directory)939940### Background subprocess941942```sh943# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 944why, one step back944npm run build &Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 945–947why, one step back945```946947```jsImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 948–949why, one step back948// zx949await $({detached: true})`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 950–953why, one step back950```951952```js953// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 954why, one step back954await $({detached: true})`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 955–970why, one step back955```956957[More info.](environment.md#background-subprocess)958959### IPC960961```sh962# Bash does not allow simple IPC963```964965```js966// zx does not allow simple IPC967```968969```js970// ExecaAdd promise-based IPC (#1059)ehmickybefore adoptionacc2b68
line 971why, one step back971const subprocess = $({node: true})`script.js`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
line 972why, one step back972Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
line 973why, one step back973for await (const message of subprocess.getEachMessage()) {Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
line 974why, one step back974 if (message === 'ping') {Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
line 975why, one step back975 await subprocess.sendMessage('pong');Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 976–1004why, one step back976 }977});978```979980[More info.](ipc.md)981982### Transforms983984```sh985# Bash does not allow transforms986```987988```js989// zx does not allow transforms990```991992```js993// Execa994const transform = function * (line) {995 if (!line.includes('secret')) {996 yield line;997 }998};9991000await $({stdout: [transform, 'inherit']})`echo ${'This is a secret.'}`;1001```10021003[More info.](transform.md)1004Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 1005why, one step back1005### Signal terminationImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 1006–1018why, one step back10061007```sh1008# Bash1009kill $PID1010```10111012```js1013// zx1014subprocess.kill();1015```10161017```js1018// ExecaImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 1019–1021why, one step back1019subprocess.kill();10201021// Or with an error message and stack trace:Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
line 1022why, one step back1022subprocess.kill(error);Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 1023why, one step back1023```Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
line 1024why, one step back1024Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 1025–1053why, one step back1025[More info.](termination.md#signal-termination)10261027### Default signal10281029```sh1030# Bash does not allow changing the default termination signal1031```10321033```js1034// zx only allows changing the signal used for timeouts1035const $$ = $({timeoutSignal: 'SIGINT'});1036```10371038```js1039// Execa1040const $ = $_({killSignal: 'SIGINT'});1041```10421043[More info.](termination.md#default-signal)10441045### Cancelation10461047```sh1048# Bash1049kill $PID1050```10511052```js1053// zxImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 1054–1057why, one step back1054const controller = new AbortController();1055await $({signal: controller.signal})`node long-script.js`;1056```1057Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 1058–1063why, one step back1058```js1059// Execa1060const controller = new AbortController();1061await $({cancelSignal: controller.signal})`node long-script.js`;1062```1063Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
line 1064why, one step back1064[More info.](termination.md#canceling)Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
lines 1065–1096why, one step back10651066### Graceful termination10671068```sh1069# Bash1070trap cleanup SIGTERM1071```10721073```js1074// zx1075// This does not work on Windows1076process.on('SIGTERM', () => {1077 // ...1078});1079```10801081```js1082// Execa - main.js1083const controller = new AbortController();1084await $({1085 cancelSignal: controller.signal,1086 gracefulCancel: true,1087})`node build.js`;1088```10891090```js1091// Execa - build.js1092import {getCancelSignal} from 'execa';10931094const cancelSignal = await getCancelSignal();1095await fetch('https://example.com', {signal: cancelSignal});1096```Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 1097–1104why, one step back10971098### Interleaved output10991100```sh1101# Bash prints stdout and stderr interleaved1102```11031104```jsImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 1105–1106why, one step back1105// zx1106const all = String(await $`node example.js`);Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 1107–1109why, one step back1107```11081109```jsImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 1110why, one step back1110// ExecaImprove `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 1111–1119why, one step back1111const {all} = await $({all: true})`node example.js`;1112```11131114[More info.](output.md#interleaved-output)11151116### PID11171118```sh1119# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 1120why, one step back1120npm run build &Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 1121–1129why, one step back1121echo $!1122```11231124```js1125// zx does not return `subprocess.pid`1126```11271128```js1129// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 1130why, one step back1130const {pid} = $`npm run build`;Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 1131–1133why, one step back1131```11321133[More info.](termination.md#inter-process-termination)Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 1134–1289why, one step back11341135### CLI arguments11361137```js1138// zx1139const {myCliFlag} = argv;1140```11411142```js1143// Execa1144import {parseArgs} from 'node:util';11451146const {myCliFlag} = parseArgs({strict: false}).values;1147```11481149[More info.](https://nodejs.org/api/util.html#utilparseargsconfig)11501151### CLI prompts11521153```sh1154# Bash1155read -p "Question? " answer1156```11571158```js1159// zx1160const answer = await question('Question? ');1161```11621163```js1164// Execa1165import input from '@inquirer/input';11661167const answer = await input({message: 'Question?'});1168```11691170[More info.](https://github.com/SBoudrias/Inquirer.js)11711172### CLI spinner11731174```sh1175# Bash does not provide with a builtin spinner1176```11771178```js1179// zx1180await spinner(() => $`node script.js`);1181```11821183```js1184// Execa1185import {oraPromise} from 'ora';11861187await oraPromise($`node script.js`);1188```11891190[More info.](https://github.com/sindresorhus/ora)11911192### Sleep11931194```sh1195# Bash1196sleep 51197```11981199```js1200// zx1201await sleep(5000);1202```12031204```js1205// Execa1206import {setTimeout} from 'node:timers/promises';12071208await setTimeout(5000);1209```12101211[More info.](https://nodejs.org/api/timers.html#timerspromisessettimeoutdelay-value-options)12121213### Globbing12141215```sh1216# Bash1217ls packages/*1218```12191220```js1221// zx1222const files = await glob(['packages/*']);1223```12241225```js1226// Execa1227import {glob} from 'node:fs/promises';12281229const files = await Array.fromAsync(glob('packages/*'));1230```12311232[More info.](https://nodejs.org/api/fs.html#fspromisesglobpattern-options)12331234### Temporary file12351236```js1237// zx1238const filePath = tmpfile();1239```12401241```js1242// Execa1243import tempfile from 'tempfile';12441245const filePath = tempfile();1246```12471248[More info.](https://github.com/sindresorhus/tempfile)12491250### HTTP requests12511252```sh1253# Bash1254curl https://github.com1255```12561257```js1258// zx1259await fetch('https://github.com');1260```12611262```js1263// Execa1264await fetch('https://github.com');1265```12661267[More info.](https://nodejs.org/api/globals.html#fetch)12681269### Retry on error12701271```js1272// zx1273await retry(1274 5,1275 () => $`curl -sSL https://sindresorhus.com/unicorn`,1276)1277```12781279```js1280// Execa1281import pRetry from 'p-retry';12821283await pRetry(1284 () => $`curl -sSL https://sindresorhus.com/unicorn`,1285 {retries: 5},1286);1287```12881289[More info.](https://github.com/sindresorhus/p-retry)Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 1290–1292why, one step back12901291<hr>1292Add documentation about nano-spawn (#1157)ehmickybefore adoptioneb3cfba
line 1293why, one step back1293[**Next**: 🐭 Small packages](small.md)\Improve `readme.md` (#999)ehmickybefore adoptionaca3db3
lines 1294–1295why, one step back1294[**Previous**: 📎 Windows](windows.md)\1295[**Top**: Table of contents](../readme.md#documentation)