Skip to content
Myr

bash.md

This file

Path

docs/bash.md

894 lines · 15.1 KiB · Markdown

Last changed by

Add documentation about TypeScript types (#1015)ehmickybefore adoptionf79e058

History of this file

Take it

Show it rendered

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) (which inspired this feature). Execa intends to be more:10- [Performant](#performance)11- [Cross-platform](#shell): [no shell](shell.md) is used, only JavaScript.12- [Secure](#escaping): no shell injection.13- [Simple](#simplicity): minimalistic API, no [globals](#global-variables), no [binary](#main-binary), no [builtin CLI utilities](#builtin-utilities).14- [Featureful](#simplicity): all Execa features are available ([text lines iteration](#iterate-over-output-lines), [subprocess piping](#piping-stdout-to-another-command), [IPC](#ipc), [transforms](#transforms), [background subprocesses](#background-subprocess), [cancelation](#cancelation), [local binaries](#local-binaries), [cleanup on exit](termination.md#current-process-exit), [interleaved output](#interleaved-output), [forceful termination](termination.md#forceful-termination), and [more](../readme.md#documentation)).15- [Easy to debug](#debugging): [verbose mode](#verbose-mode), [detailed errors](#errors), [messages and stack traces](#cancelation), stateless API.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](#builtin-utilities).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). Unlike zx, it lets you use [any of its native features](#background-subprocess): [`pid`](#pid), [IPC](ipc.md), [`unref()`](https://nodejs.org/api/child_process.html#subprocessunref), [`detached`](environment.md#background-subprocess), [`uid`](windows.md#uid-and-gid), [`gid`](windows.md#uid-and-gid), [`cancelSignal`](termination.md#canceling), etc.3839## Modularity4041zx includes many builtin utilities: `fetch()`, `question()`, `sleep()`, `stdin()`, `retry()`, `spinner()`, `chalk`, `fs-extra`, `os`, `path`, `globby`, `yaml`, `minimist`, `which`, Markdown scripts, remote scripts.4243Execa does not include [any utility](#builtin-utilities): it focuses on being small and modular instead. Any Node.js package can be used in your scripts.4445## Performance4647Spawning a shell for every command comes at a performance cost, which Execa avoids.4849Also, [local binaries](#local-binaries) can be directly executed without using `npx`.5051## Debugging5253Subprocesses can be hard to debug, which is why Execa includes a [`verbose`](#verbose-mode) option.5455Also, Execa's error messages and [properties](#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).5657Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.5859## Examples6061### Main binary6263```sh64# Bash65bash file.sh66```6768```js69// zx70zx file.js7172// or a shebang can be used:73//   #!/usr/bin/env zx74```7576```js77// Execa scripts are just regular Node.js files78node file.js79```8081### Global variables8283```js84// zx85await $`npm run build`;86```8788```js89// Execa90import {$} from 'execa';9192await $`npm run build`;93```9495[More info.](execution.md)9697### Command execution9899```sh100# Bash101npm run build102```103104```js105// zx106await $`npm run build`;107```108109```js110// Execa111await $`npm run build`;112```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 timeout = '5s';289await $`npm run init`.timeout(timeout);290await $`npm run build`.timeout(timeout);291await $`npm run test`.timeout(timeout);292```293294```js295// Execa296import {$ as $_} from 'execa';297298const $ = $_({timeout: 5000});299300await $`npm run init`;301await $`npm run build`;302await $`npm run test`;303```304305[More info.](execution.md#globalshared-options)306307### Environment variables308309```sh310# Bash311EXAMPLE=1 npm run build312```313314```js315// zx316$.env.EXAMPLE = '1';317await $`npm run build`;318delete $.env.EXAMPLE;319```320321```js322// Execa323await $({env: {EXAMPLE: '1'}})`npm run build`;324```325326[More info.](input.md#environment-variables)327328### Local binaries329330```sh331# Bash332npx tsc --version333```334335```js336// zx337await $`npx tsc --version`;338```339340```js341// Execa342await $`tsc --version`;343```344345[More info.](environment.md#local-binaries)346347### Builtin utilities348349```js350// zx351const content = await stdin();352```353354```js355// Execa356import getStdin from 'get-stdin';357358const content = await getStdin();359```360361### Printing to stdout362363```sh364# Bash365echo example366```367368```js369// zx370echo`example`;371```372373```js374// Execa375console.log('example');376```377378### Silent stderr379380```sh381# Bash382npm run build 2> /dev/null383```384385```js386// zx387await $`npm run build`.stdio('inherit', 'pipe', 'ignore');388```389390```js391// Execa does not print stdout/stderr by default392await $`npm run build`;393```394395### Verbose mode396397```sh398# Bash399set -v400npm run build401```402403```js404// zx >=8405await $`npm run build`.verbose();406407// or:408$.verbose = true;409```410411```js412// Execa413await $({verbose: 'full'})`npm run build`;414```415416Or:417418```419NODE_DEBUG=execa node file.js420```421422Which prints:423424```425[19:49:00.360] [0] $ npm run build426Building...427Done.428[19:49:00.383] [0] √ (done in 23ms)429```430431[More info.](debugging.md#verbose-mode)432433### Piping stdout to another command434435```sh436# Bash437echo npm run build | sort | head -n2438```439440```js441// zx442await $`npm run build | sort | head -n2`;443```444445```js446// Execa447await $`npm run build`448	.pipe`sort`449	.pipe`head -n2`;450```451452[More info.](pipe.md)453454### Piping stdout and stderr to another command455456```sh457# Bash458npm run build |& cat459```460461```js462// zx463const subprocess = $`npm run build`;464const cat = $`cat`;465subprocess.pipe(cat);466subprocess.stderr.pipe(cat.stdin);467await Promise.all([subprocess, cat]);468```469470```js471// Execa472await $({all: true})`npm run build`473	.pipe({from: 'all'})`cat`;474```475476[More info.](pipe.md#source-file-descriptor)477478### Piping stdout to a file479480```sh481# Bash482npm run build > output.txt483```484485```js486// zx487import {createWriteStream} from 'node:fs';488489await $`npm run build`.pipe(createWriteStream('output.txt'));490```491492```js493// Execa494await $({stdout: {file: 'output.txt'}})`npm run build`;495```496497[More info.](output.md#file-output)498499### Piping interleaved stdout and stderr to a file500501```sh502# Bash503npm run build &> output.txt504```505506```js507// zx508import {createWriteStream} from 'node:fs';509510const subprocess = $`npm run build`;511const fileStream = createWriteStream('output.txt');512subprocess.pipe(fileStream);513subprocess.stderr.pipe(fileStream);514await subprocess;515```516517```js518// Execa519const output = {file: 'output.txt'};520await $({stdout: output, stderr: output})`npm run build`;521```522523[More info.](output.md#file-output)524525### Piping stdin from a file526527```sh528# Bash529cat < input.txt530```531532```js533// zx534const cat = $`cat`;535fs.createReadStream('input.txt').pipe(cat.stdin);536await cat;537```538539```js540// Execa541await $({inputFile: 'input.txt'})`cat`;542```543544[More info.](input.md#file-input)545546### Iterate over output lines547548```sh549# Bash550while read551do552	if [[ "$REPLY" == *ERROR* ]]553	then554		echo "$REPLY"555	fi556done < <(npm run build)557```558559```js560// zx does not allow proper iteration.561// For example, the iteration does not handle subprocess errors.562```563564```js565// Execa566for await (const line of $`npm run build`) {567	if (line.includes('ERROR')) {568		console.log(line);569	}570}571```572573[More info.](lines.md#progressive-splitting)574575### Errors576577```sh578# Bash communicates errors only through the exit code and stderr579timeout 1 sleep 2580echo $?581```582583```js584// zx585const {586	stdout,587	stderr,588	exitCode,589	signal,590} = await $`sleep 2`.timeout('1s');591// file:///home/me/Desktop/node_modules/zx/build/core.js:146592//             let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);593//                          ^594// ProcessOutput [Error]:595//     at file:///home/me/Desktop/example.js:2:20596//     exit code: null597//     signal: SIGTERM598//     at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)599//     at ChildProcess.emit (node:events:512:28)600//     at maybeClose (node:internal/child_process:1098:16)601//     at Socket.<anonymous> (node:internal/child_process:456:11)602//     at Socket.emit (node:events:512:28)603//     at Pipe.<anonymous> (node:net:316:12)604//     at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {605//   _code: null,606//   _signal: 'SIGTERM',607//   _stdout: '',608//   _stderr: '',609//   _combined: ''610// }611```612613```js614// Execa615const {616	stdout,617	stderr,618	exitCode,619	signal,620	signalDescription,621	originalMessage,622	shortMessage,623	command,624	escapedCommand,625	failed,626	timedOut,627	isCanceled,628	isTerminated,629	isMaxBuffer,630	// and other error-related properties: code, etc.631} = await $({timeout: 1})`sleep 2`;632// ExecaError: Command timed out after 1 milliseconds: sleep 2633//     at file:///home/me/Desktop/example.js:2:20634//     at ... {635//   shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',636//   originalMessage: '',637//   command: 'sleep 2',638//   escapedCommand: 'sleep 2',639//   cwd: '/path/to/cwd',640//   durationMs: 19.95693,641//   failed: true,642//   timedOut: true,643//   isCanceled: false,644//   isTerminated: true,645//   isMaxBuffer: false,646//   signal: 'SIGTERM',647//   signalDescription: 'Termination',648//   stdout: '',649//   stderr: '',650//   stdio: [undefined, '', ''],651//   pipedFrom: []652// }653```654655[More info.](errors.md)656657### Exit codes658659```sh660# Bash661npm run build662echo $?663```664665```js666// zx667const {exitCode} = await $`npm run build`.nothrow();668echo`${exitCode}`;669```670671```js672// Execa673const {exitCode} = await $({reject: false})`npm run build`;674console.log(exitCode);675```676677[More info.](errors.md#exit-code)678679### Timeouts680681```sh682# Bash683timeout 5 npm run build684```685686```js687// zx688await $`npm run build`.timeout('5s');689```690691```js692// Execa693await $({timeout: 5000})`npm run build`;694```695696[More info.](termination.md#timeout)697698### Current filename699700```sh701# Bash702echo "$(basename "$0")"703```704705```js706// zx707await $`echo ${__filename}`;708```709710```js711// Execa712await $`echo ${import.meta.filename}`;713```714715### Current directory716717```sh718# Bash719cd project720```721722```js723// zx724cd('project');725726// or:727$.cwd = 'project';728```729730```js731// Execa732const $$ = $({cwd: 'project'});733```734735[More info.](environment.md#current-directory)736737### Multiple current directories738739```sh740# Bash741pushd project742pwd743popd744pwd745```746747```js748// zx749within(async () => {750	cd('project');751	await $`pwd`;752});753754await $`pwd`;755```756757```js758// Execa759await $({cwd: 'project'})`pwd`;760await $`pwd`;761```762763[More info.](environment.md#current-directory)764765### Background subprocess766767```sh768# Bash769npm run build &770```771772```js773// zx does not allow setting the `detached` option774```775776```js777// Execa778await $({detached: true})`npm run build`;779```780781[More info.](environment.md#background-subprocess)782783### IPC784785```sh786# Bash does not allow simple IPC787```788789```js790// zx does not allow simple IPC791```792793```js794// Execa795const subprocess = $({ipc: true})`node script.js`;796797subprocess.on('message', message => {798	if (message === 'ping') {799		subprocess.send('pong');800	}801});802```803804[More info.](ipc.md)805806### Transforms807808```sh809# Bash does not allow transforms810```811812```js813// zx does not allow transforms814```815816```js817// Execa818const transform = function * (line) {819	if (!line.includes('secret')) {820		yield line;821	}822};823824await $({stdout: [transform, 'inherit']})`echo ${'This is a secret.'}`;825```826827[More info.](transform.md)828829### Cancelation830831```sh832# Bash833kill $PID834```835836```js837// zx838subprocess.kill();839```840841```js842// Execa843// Can specify an error message and stack trace844subprocess.kill(error);845846// Or use an `AbortSignal`847const controller = new AbortController();848await $({signal: controller.signal})`node long-script.js`;849```850851[More info.](termination.md#canceling)852853### Interleaved output854855```sh856# Bash prints stdout and stderr interleaved857```858859```js860// zx separates stdout and stderr861const {stdout, stderr} = await $`node example.js`;862```863864```js865// Execa can interleave stdout and stderr866const {all} = await $({all: true})`node example.js`;867```868869[More info.](output.md#interleaved-output)870871### PID872873```sh874# Bash875npm run build &876echo $!877```878879```js880// zx does not return `subprocess.pid`881```882883```js884// Execa885const {pid} = $`npm run build`;886```887888[More info.](termination.md#inter-process-termination)889890<hr>891892[**Next**: 🤓 TypeScript](typescript.md)\893[**Previous**: 📎 Windows](windows.md)\894[**Top**: Table of contents](../readme.md#documentation)