bash.md
This file
Path
docs/bash.md
1,295 lines · 21.0 KiB · Markdown
Last changed by
Fix documentation and types mistakesSindre Sorhusbefore adoption74b854a
History of this fileTake it
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 zx89This 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.11- [Cross-platform](#shell): [no shell](shell.md) is used, only JavaScript.12- [Secure](#escaping): no shell injection.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)).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)1617## Flexibility1819Unlike 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.2021## 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.3637Execa 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.3839## Modularity4041zx 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.4243Execa 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.4445## Performance4647Spawning a shell for every command comes at a performance cost, which Execa avoids.4849## Debugging5051Subprocesses 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.5253Also, 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).5455Finally, 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// zx83await $`npm run build`;84```8586```js87// Execa88import {$} from 'execa';8990await $`npm run build`;91```9293[More info.](execution.md)9495### Command execution9697```sh98# Bash99npm run build100```101102```js103// zx104await $`npm run build`;105```106107```js108// Execa109await $`npm run build`;110```111112[More info.](execution.md)113114### 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# Bash223echo "$(npm run build)"224```225226```js227// zx228const result = await $`npm run build`;229await $`echo ${result}`;230```231232```js233// Execa234const result = await $`npm run build`;235await $`echo ${result}`;236```237238[More info.](execution.md#subcommands)239240### Serial commands241242```sh243# Bash244npm run build && npm run test245```246247```js248// zx249await $`npm run build && npm run test`;250```251252```js253// Execa254await $`npm run build`;255await $`npm run test`;256```257258### Parallel commands259260```sh261# Bash262npm run build &263npm run test &264```265266```js267// zx268await Promise.all([$`npm run build`, $`npm run test`]);269```270271```js272// Execa273await Promise.all([$`npm run build`, $`npm run test`]);274```275276### Global/shared options277278```sh279# Bash280options="timeout 5"281$options npm run init282$options npm run build283$options npm run test284```285286```js287// zx288const $$ = $({verbose: true});289290await $$`npm run init`;291await $$`npm run build`;292await $$`npm run test`;293```294295```js296// Execa297import {$ as $_} from 'execa';298299const $ = $_({verbose: 'short'});300301await $`npm run init`;302await $`npm run build`;303await $`npm run test`;304```305306[More info.](execution.md#globalshared-options)307308### Environment variables309310```sh311# Bash312EXAMPLE=1 npm run build313```314315```js316// zx317await $({env: {EXAMPLE: '1'}})`npm run build`;318```319320```js321// Execa322await $({env: {EXAMPLE: '1'}})`npm run build`;323```324325[More info.](input.md#environment-variables)326327### Local binaries328329```sh330# Bash331npx tsc --version332```333334```js335// zx336await $({preferLocal: true})`tsc --version`;337```338339```js340// Execa341await $({preferLocal: true})`tsc --version`;342```343344[More info.](environment.md#local-binaries)345346### Retrieve stdin347348```sh349# Bash350read content351```352353```js354// zx355const content = await stdin();356```357358```js359// Execa360import getStdin from 'get-stdin';361362const content = await getStdin();363```364365[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)439440### Printing to stdout441442```sh443# Bash444echo example445```446447```js448// zx449echo`example`;450```451452```js453// Execa454console.log('example');455```456457### Silent stdout458459```sh460# Bash461npm run build > /dev/null462```463464```js465// zx466await $`npm run build`.quiet();467```468469```js470// Execa does not print stdout by default471await $`npm run build`;472```473474### Binary output475476```sh477# 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```sh496# Bash497set -v498npm run build499set +v500```501502```js503// zx504await $`npm run build`.verbose();505```506507```js508// Execa509await $({verbose: 'full'})`npm run build`;510```511512[More info.](debugging.md#verbose-mode)513514### Verbose mode (global)515516```sh517# Bash518set -v519npm run build520```521522```523// zx524$ zx --verbose file.js525$ npm run build526Building...527Done.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.535[19:49:00.383] [0] √ (done in 23ms)536```537538[More info.](debugging.md#global-mode)539540### Piping stdout to another command541542```sh543# Bash544echo npm run build | sort | head -n2545```546547```js548// zx549await $`npm run build`550 .pipe($`sort`)551 .pipe($`head -n2`);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# Bash567npm run build |& cat568```569570```js571// zx572const subprocess = $`npm run build`;573const cat = $`cat`;574subprocess.pipe(cat);575subprocess.stderr.pipe(cat.stdin);576await Promise.all([subprocess, cat]);577```578579```js580// Execa581await $({all: true})`npm run build`582 .pipe({from: 'all'})`cat`;583```584585[More info.](pipe.md#source-file-descriptor)586587### Piping stdout to a file588589```sh590# Bash591npm run build > output.txt592```593594```js595// zx596import {createWriteStream} from 'node:fs';597598await $`npm run build`.pipe(createWriteStream('output.txt'));599```600601```js602// Execa603await $({stdout: {file: 'output.txt'}})`npm run build`;604```605606[More info.](output.md#file-output)607608### 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)628629### 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)654655### Piping stdin from a file656657```sh658# Bash659cat < input.txt660```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)675676### 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)787788### Iterate over output lines789790```sh791# Bash792while read793do794 if [[ "$REPLY" == *ERROR* ]]795 then796 echo "$REPLY"797 fi798done < <(npm run build)799```800801```js802// zx does not allow easily iterating over output lines.803// Also, the iteration does not handle subprocess errors.804```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)816817### Detailed errors818819```sh820# Bash communicates errors only through the exit code and stderr821timeout 1 sleep 2822echo $?823```824825```js826// zx827await $`sleep 2`.timeout('1ms');828// Error:829// at file:///home/me/Desktop/example.js:6:12830// exit code: null831// signal: SIGTERM832```833834```js835// Execa836await $({timeout: 1})`sleep 2`;837// 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# Bash866npm run build867echo $?868```869870```js871// zx872const {exitCode} = await $`npm run build`.nothrow();873```874875```js876// Execa877const {exitCode} = await $({reject: false})`npm run build`;878```879880[More info.](errors.md#exit-code)881882### Timeouts883884```sh885# Bash886timeout 5 npm run build887```888889```js890// zx891await $`npm run build`.timeout('5s');892```893894```js895// Execa896await $({timeout: 5000})`npm run build`;897```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// zx927const $$ = $({cwd: 'project'});928929// Or:930cd('project');931```932933```js934// Execa935const $$ = $({cwd: 'project'});936```937938[More info.](environment.md#current-directory)939940### Background subprocess941942```sh943# Bash944npm run build &945```946947```js948// zx949await $({detached: true})`npm run build`;950```951952```js953// Execa954await $({detached: true})`npm run build`;955```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// Execa971const subprocess = $({node: true})`script.js`;972973for await (const message of subprocess.getEachMessage()) {974 if (message === 'ping') {975 await subprocess.sendMessage('pong');976 }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)10041005### Signal termination10061007```sh1008# Bash1009kill $PID1010```10111012```js1013// zx1014subprocess.kill();1015```10161017```js1018// Execa1019subprocess.kill();10201021// Or with an error message and stack trace:1022subprocess.kill(error);1023```10241025[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// zx1054const controller = new AbortController();1055await $({signal: controller.signal})`node long-script.js`;1056```10571058```js1059// Execa1060const controller = new AbortController();1061await $({cancelSignal: controller.signal})`node long-script.js`;1062```10631064[More info.](termination.md#canceling)10651066### 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```10971098### Interleaved output10991100```sh1101# Bash prints stdout and stderr interleaved1102```11031104```js1105// zx1106const all = String(await $`node example.js`);1107```11081109```js1110// Execa1111const {all} = await $({all: true})`node example.js`;1112```11131114[More info.](output.md#interleaved-output)11151116### PID11171118```sh1119# Bash1120npm run build &1121echo $!1122```11231124```js1125// zx does not return `subprocess.pid`1126```11271128```js1129// Execa1130const {pid} = $`npm run build`;1131```11321133[More info.](termination.md#inter-process-termination)11341135### 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)12901291<hr>12921293[**Next**: 🐭 Small packages](small.md)\1294[**Previous**: 📎 Windows](windows.md)\1295[**Top**: Table of contents](../readme.md#documentation)