bash.md
This file
Path
docs/bash.md
865 lines · 14.4 KiB · Markdown
Last changed by
Move API reference to its own page (#996)ehmickybefore adoption7cde496
History of this fileTake it
Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 1–862why, 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 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 $`echo example`;86```8788```js89// Execa90import {$} from 'execa';9192await $`echo example`;93```9495[More info.](execution.md)9697### Command execution9899```sh100# Bash101echo example102```103104```js105// zx106await $`echo example`;107```108109```js110// Execa111await $`echo example`;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 "$(echo example)"224```225226```js227// zx228const example = await $`echo example`;229await $`echo ${example}`;230```231232```js233// Execa234const example = await $`echo example`;235await $`echo ${example}`;236```237238[More info.](execution.md#subcommands)239240### Serial commands241242```sh243# Bash244echo one && echo two245```246247```js248// zx249await $`echo one && echo two`;250```251252```js253// Execa254await $`echo one`;255await $`echo two`;256```257258### Parallel commands259260```sh261# Bash262echo one &263echo two &264```265266```js267// zx268await Promise.all([$`echo one`, $`echo two`]);269```270271```js272// Execa273await Promise.all([$`echo one`, $`echo two`]);274```275276### Global/shared options277278```sh279# Bash280options="timeout 5"281$options echo one282$options echo two283$options echo three284```285286```js287// zx288const timeout = '5s';289await $`echo one`.timeout(timeout);290await $`echo two`.timeout(timeout);291await $`echo three`.timeout(timeout);292```293294```js295// Execa296import {$ as $_} from 'execa';297298const $ = $_({timeout: 5000});299300await $`echo one`;301await $`echo two`;302await $`echo three`;303```304305[More info.](execution.md#globalshared-options)306307### Environment variables308309```sh310# Bash311EXAMPLE=1 example_command312```313314```js315// zx316$.env.EXAMPLE = '1';317await $`example_command`;318delete $.env.EXAMPLE;319```320321```js322// Execa323await $({env: {EXAMPLE: '1'}})`example_command`;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# Bash382echo example 2> /dev/null383```384385```js386// zx387await $`echo example`.stdio('inherit', 'pipe', 'ignore');388```389390```js391// Execa does not print stdout/stderr by default392await $`echo example`;393```394395### Verbose mode396397```sh398# Bash399set -v400echo example401```402403```js404// zx >=8405await $`echo example`.verbose();406407// or:408$.verbose = true;409```410411```js412// Execa413await $({verbose: 'full'})`echo example`;414```415416Or:417418```419NODE_DEBUG=execa node file.js420```421422Which prints:423424```425[19:49:00.360] [0] $ echo example426example427[19:49:00.383] [0] √ (done in 23ms)428```429430[More info.](debugging.md#verbose-mode)431432### Piping stdout to another command433434```sh435# Bash436echo npm run build | sort | head -n2437```438439```js440// zx441await $`npm run build | sort | head -n2`;442```443444```js445// Execa446await $`npm run build`447 .pipe`sort`448 .pipe`head -n2`;449```450451[More info.](pipe.md)452453### Piping stdout and stderr to another command454455```sh456# Bash457echo example |& cat458```459460```js461// zx462const echo = $`echo example`;463const cat = $`cat`;464echo.pipe(cat)465echo.stderr.pipe(cat.stdin);466await Promise.all([echo, cat]);467```468469```js470// Execa471await $({all: true})`echo example`472 .pipe({from: 'all'})`cat`;473```474475[More info.](pipe.md#source-file-descriptor)476477### Piping stdout to a file478479```sh480# Bash481echo example > output.txt482```483484```js485// zx486await $`echo example`.pipe(fs.createWriteStream('output.txt'));487```488489```js490// Execa491await $({stdout: {file: 'output.txt'}})`echo example`;492```493494[More info.](output.md#file-output)495496### Piping stdin from a file497498```sh499# Bash500echo example < input.txt501```502503```js504// zx505const cat = $`cat`;506fs.createReadStream('input.txt').pipe(cat.stdin);507await cat;508```509510```js511// Execa512await $({inputFile: 'input.txt'})`cat`;513```514515[More info.](input.md#file-input)516517### Iterate over output lines518519```sh520# Bash521while read522do523 if [[ "$REPLY" == *ERROR* ]]524 then525 echo "$REPLY"526 fi527done < <(npm run build)528```529530```js531// zx does not allow proper iteration.532// For example, the iteration does not handle subprocess errors.533```534535```js536// Execa537for await (const line of $`npm run build`) {538 if (line.includes('ERROR')) {539 console.log(line);540 }541}542```543544[More info.](lines.md#progressive-splitting)545546### Errors547548```sh549# Bash communicates errors only through the exit code and stderr550timeout 1 sleep 2551echo $?552```553554```js555// zx556const {557 stdout,558 stderr,559 exitCode,560 signal,561} = await $`sleep 2`.timeout('1s');562// file:///home/me/Desktop/node_modules/zx/build/core.js:146563// let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);564// ^565// ProcessOutput [Error]:566// at file:///home/me/Desktop/example.js:2:20567// exit code: null568// signal: SIGTERM569// at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)570// at ChildProcess.emit (node:events:512:28)571// at maybeClose (node:internal/child_process:1098:16)572// at Socket.<anonymous> (node:internal/child_process:456:11)573// at Socket.emit (node:events:512:28)574// at Pipe.<anonymous> (node:net:316:12)575// at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {576// _code: null,577// _signal: 'SIGTERM',578// _stdout: '',579// _stderr: '',580// _combined: ''581// }582```583584```js585// Execa586const {587 stdout,588 stderr,589 exitCode,590 signal,591 signalDescription,592 originalMessage,593 shortMessage,594 command,595 escapedCommand,596 failed,597 timedOut,598 isCanceled,599 isTerminated,600 isMaxBuffer,601 // and other error-related properties: code, etc.602} = await $({timeout: 1})`sleep 2`;603// ExecaError: Command timed out after 1 milliseconds: sleep 2604// at file:///home/me/Desktop/example.js:2:20605// at ... {606// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',607// originalMessage: '',608// command: 'sleep 2',609// escapedCommand: 'sleep 2',610// cwd: '/path/to/cwd',611// durationMs: 19.95693,612// failed: true,613// timedOut: true,614// isCanceled: false,615// isTerminated: true,616// isMaxBuffer: false,617// signal: 'SIGTERM',618// signalDescription: 'Termination',619// stdout: '',620// stderr: '',621// stdio: [undefined, '', ''],622// pipedFrom: []623// }624```625626[More info.](errors.md)627628### Exit codes629630```sh631# Bash632false633echo $?634```635636```js637// zx638const {exitCode} = await $`false`.nothrow();639echo`${exitCode}`;640```641642```js643// Execa644const {exitCode} = await $({reject: false})`false`;645console.log(exitCode);646```647648[More info.](errors.md#exit-code)649650### Timeouts651652```sh653# Bash654timeout 5 echo example655```656657```js658// zx659await $`echo example`.timeout('5s');660```661662```js663// Execa664await $({timeout: 5000})`echo example`;665```666667[More info.](termination.md#timeout)668669### Current filename670671```sh672# Bash673echo "$(basename "$0")"674```675676```js677// zx678await $`echo ${__filename}`;679```680681```js682// Execa683await $`echo ${import.meta.filename}`;684```685686### Current directory687688```sh689# Bash690cd project691```692693```js694// zx695cd('project');696697// or:698$.cwd = 'project';699```700701```js702// Execa703const $$ = $({cwd: 'project'});704```705706[More info.](environment.md#current-directory)707708### Multiple current directories709710```sh711# Bash712pushd project713pwd714popd715pwd716```717718```js719// zx720within(async () => {721 cd('project');722 await $`pwd`;723});724725await $`pwd`;726```727728```js729// Execa730await $({cwd: 'project'})`pwd`;731await $`pwd`;732```733734[More info.](environment.md#current-directory)735736### Background subprocess737738```sh739# Bash740echo one &741```742743```js744// zx does not allow setting the `detached` option745```746747```js748// Execa749await $({detached: true})`echo one`;750```751752[More info.](environment.md#background-subprocess)753754### IPC755756```sh757# Bash does not allow simple IPC758```759760```js761// zx does not allow simple IPC762```763764```js765// Execa766const subprocess = $({ipc: true})`node script.js`;767768subprocess.on('message', message => {769 if (message === 'ping') {770 subprocess.send('pong');771 }772});773```774775[More info.](ipc.md)776777### Transforms778779```sh780# Bash does not allow transforms781```782783```js784// zx does not allow transforms785```786787```js788// Execa789const transform = function * (line) {790 if (!line.includes('secret')) {791 yield line;792 }793};794795await $({stdout: [transform, 'inherit']})`echo ${'This is a secret.'}`;796```797798[More info.](transform.md)799800### Cancelation801802```sh803# Bash804kill $PID805```806807```js808// zx809subprocess.kill();810```811812```js813// Execa814// Can specify an error message and stack trace815subprocess.kill(error);816817// Or use an `AbortSignal`818const controller = new AbortController();819await $({signal: controller.signal})`node long-script.js`;820```821822[More info.](termination.md#canceling)823824### Interleaved output825826```sh827# Bash prints stdout and stderr interleaved828```829830```js831// zx separates stdout and stderr832const {stdout, stderr} = await $`node example.js`;833```834835```js836// Execa can interleave stdout and stderr837const {all} = await $({all: true})`node example.js`;838```839840[More info.](output.md#interleaved-output)841842### PID843844```sh845# Bash846echo example &847echo $!848```849850```js851// zx does not return `subprocess.pid`852```853854```js855// Execa856const {pid} = $`echo example`;857```858859[More info.](termination.md#inter-process-termination)860861<hr>862Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 863why, one step back863[**Next**: 📔 API reference](api.md)\Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 864–865why, one step back864[**Previous**: 📎 Windows](windows.md)\865[**Top**: Table of contents](../readme.md#documentation)