bash.md
This file
Path
docs/bash.md
1,242 lines · 20.1 KiB · Markdown
Last changed by
Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
History of this fileTake it
Add user guides (#989)ehmickybefore adoptionbe91ecf
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.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 11–12why, one step back11- [Cross-platform](#shell): [no shell](shell.md) is used, only JavaScript.12- [Secure](#escaping): no shell injection.Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 13–15why, 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), [forceful termination](termination.md#forceful-termination), and [more](../readme.md#documentation)).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 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.Add user guides (#989)ehmickybefore adoptionbe91ecf
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.Add user guides (#989)ehmickybefore adoptionbe91ecf
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.Add user guides (#989)ehmickybefore adoptionbe91ecf
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.Add user guides (#989)ehmickybefore adoptionbe91ecf
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.Add user guides (#989)ehmickybefore adoptionbe91ecf
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).Add user guides (#989)ehmickybefore adoptionbe91ecf
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`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 84–89why, one step back84```8586```js87// Execa88import {$} from 'execa';89Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
line 90why, one step back90await $`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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 buildAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 100–103why, one step back100```101102```js103// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 104why, one step back104await $`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 105–108why, one step back105```106107```js108// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 109why, one step back109await $`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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)113Add user guides (#989)ehmickybefore adoptionbe91ecf
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)"Add user guides (#989)ehmickybefore adoptionbe91ecf
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}`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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}`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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 testAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 245–248why, one step back245```246247```js248// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 249why, one step back249await $`npm run build && npm run test`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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 &Add user guides (#989)ehmickybefore adoptionbe91ecf
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`]);Add user guides (#989)ehmickybefore adoptionbe91ecf
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`]);Add user guides (#989)ehmickybefore adoptionbe91ecf
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 testAdd user guides (#989)ehmickybefore adoptionbe91ecf
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`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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});Add user guides (#989)ehmickybefore adoptionbe91ecf
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`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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 buildAdd user guides (#989)ehmickybefore adoptionbe91ecf
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`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 318–321why, one step back318```319320```js321// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 322why, one step back322await $({env: {EXAMPLE: '1'}})`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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 stdinAdd user guides (#989)ehmickybefore adoptionbe91ecf
line 347why, one step back347Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 348–352why, one step back348```sh349# Bash350read content351```352Add user guides (#989)ehmickybefore adoptionbe91ecf
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)439Add user guides (#989)ehmickybefore adoptionbe91ecf
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 stdoutAdd user guides (#989)ehmickybefore adoptionbe91ecf
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/nullAdd user guides (#989)ehmickybefore adoptionbe91ecf
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();Add user guides (#989)ehmickybefore adoptionbe91ecf
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`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 472–473why, one step back472```473Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 474why, one step back474### Binary outputAdd user guides (#989)ehmickybefore adoptionbe91ecf
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```shAdd user guides (#989)ehmickybefore adoptionbe91ecf
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 +vAdd user guides (#989)ehmickybefore adoptionbe91ecf
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();Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 505–508why, one step back505```506507```js508// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 509why, one step back509await $({verbose: 'full'})`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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)Add user guides (#989)ehmickybefore adoptionbe91ecf
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 buildAdd user guides (#989)ehmickybefore adoptionbe91ecf
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.Add user guides (#989)ehmickybefore adoptionbe91ecf
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)Add user guides (#989)ehmickybefore adoptionbe91ecf
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`);Add user guides (#989)ehmickybefore adoptionbe91ecf
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 |& catAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 568–571why, one step back568```569570```js571// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 572why, one step back572const subprocess = $`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
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]);Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 577–580why, one step back577```578579```js580// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 581why, one step back581await $({all: true})`npm run build`Add user guides (#989)ehmickybefore adoptionbe91ecf
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.txtAdd user guides (#989)ehmickybefore adoptionbe91ecf
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'));Add user guides (#989)ehmickybefore adoptionbe91ecf
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`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 604–607why, one step back604```605606[More info.](output.md#file-output)607Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
lines 608–633why, one step back608### Piping interleaved stdout and stderr to a file609610```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)633Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 634–637why, one step back634### Piping stdin from a file635636```sh637# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 638why, one step back638cat < input.txtAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 639–654why, one step back639```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)654Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 655–766why, one step back655### Web streams656657```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)766Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 767–780why, one step back767### Iterate over output lines768769```sh770# Bash771while read772do773 if [[ "$REPLY" == *ERROR* ]]774 then775 echo "$REPLY"776 fi777done < <(npm run build)778```779780```jsImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 781–782why, one step back781// 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 back783```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)795Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 796why, one step back796### Detailed errorsAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 797–805why, one step back797798```sh799# Bash communicates errors only through the exit code and stderr800timeout 1 sleep 2801echo $?802```803804```js805// zxImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 806–810why, one step back806await $`sleep 2`.timeout('1ms');807// Error:808// at file:///home/me/Desktop/example.js:6:12809// exit code: null810// signal: SIGTERMAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 811–814why, one step back811```812813```js814// ExecaImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 815why, one step back815await $({timeout: 1})`sleep 2`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 816–844why, one step back816// ExecaError: Command timed out after 1 milliseconds: sleep 2817// 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# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 845why, one step back845npm run buildAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 846–850why, one step back846echo $?847```848849```js850// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 851why, one step back851const {exitCode} = await $`npm run build`.nothrow();Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 852–855why, one step back852```853854```js855// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 856why, one step back856const {exitCode} = await $({reject: false})`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 857–864why, one step back857```858859[More info.](errors.md#exit-code)860861### Timeouts862863```sh864# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 865why, one step back865timeout 5 npm run buildAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 866–869why, one step back866```867868```js869// zxImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 870why, one step back870await $`npm run build`.timeout('5s');Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 871–874why, one step back871```872873```js874// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 875why, one step back875await $({timeout: 5000})`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 876–905why, one step back876```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// zxImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 906why, one step back906const $$ = $({cwd: 'project'});Add user guides (#989)ehmickybefore adoptionbe91ecf
line 907why, one step back907Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 908–909why, one step back908// Or:909cd('project');Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 910–922why, one step back910```911912```js913// Execa914const $$ = $({cwd: 'project'});915```916917[More info.](environment.md#current-directory)918919### Background subprocess920921```sh922# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 923why, one step back923npm run build &Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 924–926why, one step back924```925926```jsImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 927–928why, one step back927// zx928await $({detached: true})`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 929–932why, one step back929```930931```js932// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 933why, one step back933await $({detached: true})`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 934–949why, one step back934```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// ExecaAdd promise-based IPC (#1059)ehmickybefore adoptionacc2b68
line 950why, one step back950const subprocess = $({node: true})`script.js`;Add user guides (#989)ehmickybefore adoptionbe91ecf
line 951why, one step back951Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
line 952why, one step back952for await (const message of subprocess.getEachMessage()) {Add user guides (#989)ehmickybefore adoptionbe91ecf
line 953why, one step back953 if (message === 'ping') {Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
line 954why, one step back954 await subprocess.sendMessage('pong');Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 955–983why, one step back955 }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)983Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 984why, one step back984### Signal terminationAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 985–997why, one step back985986```sh987# Bash988kill $PID989```990991```js992// zx993subprocess.kill();994```995996```js997// ExecaImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 998–1000why, one step back998subprocess.kill();9991000// Or with an error message and stack trace:Add user guides (#989)ehmickybefore adoptionbe91ecf
line 1001why, one step back1001subprocess.kill(error);Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 1002why, one step back1002```Add user guides (#989)ehmickybefore adoptionbe91ecf
line 1003why, one step back1003Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 1004–1032why, one step back1004[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// zxAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 1033–1036why, one step back1033const controller = new AbortController();1034await $({signal: controller.signal})`node long-script.js`;1035```1036Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 1037–1042why, one step back1037```js1038// Execa1039const controller = new AbortController();1040await $({cancelSignal: controller.signal})`node long-script.js`;1041```1042Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 1043–1051why, one step back1043[More info.](termination.md#canceling)10441045### Interleaved output10461047```sh1048# Bash prints stdout and stderr interleaved1049```10501051```jsImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 1052–1053why, one step back1052// zx1053const all = String(await $`node example.js`);Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 1054–1056why, one step back1054```10551056```jsImprove bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
line 1057why, one step back1057// ExecaAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 1058–1066why, one step back1058const {all} = await $({all: true})`node example.js`;1059```10601061[More info.](output.md#interleaved-output)10621063### PID10641065```sh1066# BashImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 1067why, one step back1067npm run build &Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 1068–1076why, one step back1068echo $!1069```10701071```js1072// zx does not return `subprocess.pid`1073```10741075```js1076// ExecaImprove documentation (#1003)ehmickybefore adoptionc8a6ed7
line 1077why, one step back1077const {pid} = $`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 1078–1080why, one step back1078```10791080[More info.](termination.md#inter-process-termination)Improve bash vs zx vs Execa documentation (#1100)ehmickybefore adoption466e594
lines 1081–1236why, one step back10811082### CLI arguments10831084```js1085// zx1086const {myCliFlag} = argv;1087```10881089```js1090// Execa1091import {parseArgs} from 'node:util';10921093const {myCliFlag} = parseArgs({strict: false}).values;1094```10951096[More info.](https://nodejs.org/api/util.html#utilparseargsconfig)10971098### CLI prompts10991100```sh1101# Bash1102read -p "Question? " answer1103```11041105```js1106// zx1107const answer = await question('Question? ');1108```11091110```js1111// Execa1112import input from '@inquirer/input';11131114const answer = await input({message: 'Question?'});1115```11161117[More info.](https://github.com/SBoudrias/Inquirer.js)11181119### CLI spinner11201121```sh1122# Bash does not provide with a builtin spinner1123```11241125```js1126// zx1127await spinner(() => $`node script.js`);1128```11291130```js1131// Execa1132import {oraPromise} from 'ora';11331134await oraPromise($`node script.js`);1135```11361137[More info.](https://github.com/sindresorhus/ora)11381139### Sleep11401141```sh1142# Bash1143sleep 51144```11451146```js1147// zx1148await sleep(5000);1149```11501151```js1152// Execa1153import {setTimeout} from 'node:timers/promises';11541155await setTimeout(5000);1156```11571158[More info.](https://nodejs.org/api/timers.html#timerspromisessettimeoutdelay-value-options)11591160### Globbing11611162```sh1163# Bash1164ls packages/*1165```11661167```js1168// zx1169const files = await glob(['packages/*']);1170```11711172```js1173// Execa1174import {glob} from 'node:fs/promises';11751176const files = await Array.fromAsync(glob('packages/*'));1177```11781179[More info.](https://nodejs.org/api/fs.html#fspromisesglobpattern-options)11801181### Temporary file11821183```js1184// zx1185const filePath = tmpfile();1186```11871188```js1189// Execa1190import tempfile from 'tempfile';11911192const filePath = tempfile();1193```11941195[More info.](https://github.com/sindresorhus/tempfile)11961197### HTTP requests11981199```sh1200# Bash1201curl https://github.com1202```12031204```js1205// zx1206await fetch('https://github.com');1207```12081209```js1210// Execa1211await fetch('https://github.com');1212```12131214[More info.](https://nodejs.org/api/globals.html#fetch)12151216### Retry on error12171218```js1219// zx1220await retry(1221 5,1222 () => $`curl -sSL https://sindresorhus.com/unicorn`,1223)1224```12251226```js1227// Execa1228import pRetry from 'p-retry';12291230await pRetry(1231 () => $`curl -sSL https://sindresorhus.com/unicorn`,1232 {retries: 5},1233);1234```12351236[More info.](https://github.com/sindresorhus/p-retry)Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 1237–1239why, one step back12371238<hr>1239Add documentation about TypeScript types (#1015)ehmickybefore adoptionf79e058
line 1240why, one step back1240[**Next**: 🤓 TypeScript](typescript.md)\Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 1241–1242why, one step back1241[**Previous**: 📎 Windows](windows.md)\1242[**Top**: Table of contents](../readme.md#documentation)