process_run shell: run commands portably
package:process_run/shell.dart runs one or many command lines from Dart on
Linux, macOS and Windows with the same script text. Each line is one
executable resolved with which semantics, started through dart:io
Process and returned as a ProcessResult. VM only (dart:io): Dart CLI
and Flutter desktop/mobile, not web.
import 'package:process_run/shell.dart';
Future<void> main() async {
var shell = Shell();
await shell.run('''
# Comments are allowed
dart --version
git status
''');
}
Guidelines
Choosing the entry point
- Start every process through process_run, tests included, never with
dart:io Process.start / Process.run: same executable resolution,
quoting and output capture everywhere, and kill() stops the whole
process tree. Each raw Process piece has a Shell equivalent, see
Driving a program.
Shell() then shell.run(script) is the primary API. Use the global
run(script) for one-off calls; it builds a Shell with the same
parameters. Both default to verbose: true (command echoed, stdout and
stderr streamed to the terminal) and throwOnError: true.
shell.runExecutableArguments(executable, arguments) runs one command from
an explicit argument list (no quoting/splitting), with the shell options.
Prefer it over string building when arguments come from variables.
- The global
runExecutableArguments(...) and
runExecutableArgumentsSync(...) (also in shell.dart) default to
verbose: false and throwOnError: false, unlike run. Check exitCode
yourself or pass throwOnError: true.
runSync / runExecutableArgumentsSync (global and on Shell) block until
the child exits, cannot receive stdin, cannot be kill()ed and ignore
noStdoutResult/noStderrResult. Use them in tests and tiny scripts only.
- A
Shell is immutable: cd, pushd, popd, cloneWithOptions return a
new Shell. shell.options exposes the ShellOptions in use and
shell.options.clone(...) derives a modified copy.
Shell(options: ShellOptions(...)) overrides every other constructor
parameter. Keep one ShellOptions when you create many shells.
Script syntax (run, runSync, runScript)
- One command per line. Lines are trimmed; empty lines are ignored; lines
starting with
#, // or /// are comments (printed only with
commentVerbose: true).
- A line ending with
^ or \ (space then the character; in a Dart
string write ' ') continues on the next line.
- No pipes, redirections,
&&, variables or loops: each line is exactly one
executable plus arguments. Do that logic in Dart.
- The first word is the executable. A plain name is searched in the shell
environment paths (
PATH plus user config paths and the running dart SDK
bin directory) and aliases; a relative path is resolved from
workingDirectory; an absolute path is used as is. On Windows the
PATHEXT extensions (.exe, .bat, .cmd...) are tried.
- Quote arguments containing spaces with double or single quotes, or build the
line with
shellArgument(value) / shellArguments(list). On Windows the
backslash is not an escape character (C:\dir is fine); on Linux/macOS a
bare backslash escapes the next character, so use shellArgument for paths
with backslashes.
ShellCommand.parse(line) and ShellCommand(executable, arguments)
build a single command object; shell.runCommand(command) runs it and
returns a ShellProcessResult. shellScriptSplitLines(script) and
shellScriptLineToArguments(line) expose the parser.
- Leave
runInShell null. It defaults to false, except on Windows where any
executable without a .exe extension (built-ins like echo, .bat
scripts) is run through the shell automatically.
Output and results
run returns List<ProcessResult> (one per command, in order). Import of
shell.dart adds outText, errText, outLines, errLines on the list
(all commands concatenated) and on each ProcessResult. outText joins
lines with \n and has no trailing newline; result.stdout is the raw
String decoded with stdoutEncoding.
shell.runScript(script) returns ShellProcessResults
(a List<ShellProcessResult>) with the same helpers plus
stdoutAsString, stderrAsString, stdoutAsUint8List,
stderrAsUint8List and processResults (the raw list). Prefer it when you
need the exact bytes or the executed command.
verbose: false captures silently; output is still available in the
results. commandVerbose: true with verbose: false prints only the
$ command line.
- Pass
stdout: / stderr: (StreamSink<List<int>>) to receive the child
output as it is produced (with verbose: true it goes to the sink instead
of the terminal). Use ShellLinesController to get a Stream<String> of
lines: Shell(stdout: controller.sink), listen to controller.stream,
controller.close() when done.
- Output is always buffered in the result. For a command whose output you
do not need at all,
ShellOptions(noStdoutResult: true) /
noStderrResult: true (or the same named parameters of the global
runExecutableArguments) discard it: the result field is null and
nothing is streamed to the terminal or to the sinks either. Ignored by
the sync variants.
- Default encoding is
systemEncoding. Pass stdoutEncoding: utf8 (and
stderrEncoding) when the tool prints UTF-8 on Windows.
ShellOptions(mode: ProcessStartMode.inheritStdio) hands the terminal to
the child (interactive tools); nothing is captured in that mode.
ShellOptions(mode: ProcessStartMode.detached) starts a program that
lives on after yours (an editor, a browser, another window): the run ends
once it started, exit code 0 (it has none), no output, and kill() leaves
it. With detachedWithStdio its pipes are the ones of the process given
to onProcess, the shell reads nothing (since 1.4.4, it threw before).
- A
stdout:/stderr: sink can be closed while the command still writes
(after a kill(), it takes time to end): it gets nothing more.
ShellLinesController never drops a line: one that is not in its
encoding is read as UTF-8 with U+FFFD for what is not text. The result of
a run is decoded strictly (FormatException on a tool printing bytes):
pass stdoutEncoding: const Utf8Codec(allowMalformed: true) for such a
tool.
Errors
- With
throwOnError: true (default) a non-zero exit code throws
ShellException. Catch it: e.message, e.shellCommand (the parsed
command), e.result (ProcessResult?, null when the executable could not
be started), e.shellProcessResult, and e.toDebugString() (message,
directory, command, exit code, out and err).
- A missing executable or a missing
workingDirectory also throws
ShellException (wrapping the ProcessException) with result == null.
- Use
Shell(throwOnError: false) when a non-zero exit code is expected
(grep, lsof, git diff --exit-code) and read result.exitCode.
run executes the script sequentially and stops at the first failing
command when throwOnError is true; the results of the earlier commands
are lost (only the exception is returned). Split the script if you need
partial results.
- Never build a
ShellException yourself; the factory constructors are for
the package.
Working directory
Shell(workingDirectory: path) or shell.cd(path). A relative cd path is
resolved against the current shell directory. shell.path returns the
effective directory.
shell = shell.pushd('sub') then shell = shell.popd() mimic the shell
builtins; popd() throws StateError when there is nothing to pop. Always
reassign the returned shell.
- Relative script paths (
dart tool/build.dart) are relative to the shell
workingDirectory, not to the Dart process directory.
stdin, long running processes and kill
- Feed input with
Shell(stdin: stream) where the stream is a
Stream<List<int>>. To feed generated text use a ShellLinesController:
Shell(stdin: input.binaryStream), input.write('...') /
input.writeln('...') (also after the run started, e.g. once the program
printed a prompt), input.close(). Closing it is the end of input of the
command: one reading its input until the end (cat, sort) only exits
then.
ShellLinesController works both ways: as stdout: / stderr: (give
its sink, listen to its stream of lines) and as stdin: (write to it,
give its binaryStream). One controller per direction.
- To forward the user's terminal input use
sharedStdIn (the program's own
stdin, shareable by several commands and prompts in turn) and call
await sharedStdIn.terminate() before the program ends (otherwise it
never exits). At the end of its input (a pipe, < /dev/null, CI),
sharedStdIn listeners get done: lines() completes, a command given
stdin: sharedStdIn gets its end of input, and prompt,
promptConfirm and nextLine throw a StateError (no element): catch it
in a tool that may run without a terminal.
shell.kill() kills the running command and all its descendant
processes (children, grandchildren...): sigterm, then sigkill for the
ones still running after 5 s (taskkill /t /f on Windows); the pending
run future completes with ShellException. Prefer it: servers such as
dhttpd and flutter test (its browser) leave processes behind otherwise.
shell.kill(signal) sends signal to the command only (sigint to stop
the Firebase emulators), except ProcessSignal.sigkill which kills the
descendants too.
- Any process, by pid (an app started from elsewhere, a process tree):
ShellProcesses.findByExecutable(path), ShellProcesses.descendantsOf(pid),
ShellProcesses.isRunning(pid) and ShellProcesses.kill(pids, tree: true)
(sigterm, sigkill after timeout, 5 s by default; returns the ones still
running).
run(script, onProcess: (process) {...}) gives the dart:io Process
of each command as it starts (pid, manual kill).
- Calls on one
Shell are serialized with a lock: two concurrent
shell.run on the same instance execute one after the other. Create
distinct shells for parallel work.
Driving a program (instead of Process.start)
dart:io Process |
process_run |
Process.start(exe, args) |
shell.runExecutableArguments(exe, args): a future of the result, do not await it before driving the program |
process.stdin.write(...), .close() |
ShellLinesController input: Shell(stdin: input.binaryStream), input.write(...), input.close() (end of input) |
process.stdout lines |
ShellLinesController output: Shell(stdout: output.sink), output.stream |
await process.exitCode |
(await done).exitCode, with throwOnError: false |
| all the output after exit |
result.outLines / outText: still captured with a stdout: sink |
process.kill() |
shell.kill() (the whole tree; the run then throws ShellException, at once) |
process.kill() then await process.exitCode |
with the process of onProcess: process.kill() (the command only) or await ShellProcesses.kill([process.pid], tree: true) (what it started too); the run then ends as the command does, (await done).exitCode |
process.pid, process.exitCode at exit |
onProcess: (process) { ... }: the result of the run comes later, with the end of the output (a process left behind holds it) |
Process.run(exe, args) |
Shell(verbose: false, throwOnError: false).runExecutableArguments(exe, args); Process.run ends the input of the command, a shell leaves it open: add stdin: const Stream.empty() for a command reading it |
Process.start(..., mode: ProcessStartMode.detached) |
ShellOptions(mode: ProcessStartMode.detached): the run ends once started |
Process.killPid(pid) |
ShellProcesses.kill([pid]) |
Code meant to run on another shell context too (a remote shell, a web app)
keeps to Shell, its sinks, kill() and the process of onProcess (pid,
exit code, kill), and asks the context for the rest: shellContext
(package:process_run/utils/shell_context.dart) has which, platform,
path and shellEnvironment. The global which/whichSync,
ShellProcesses, sharedStdIn and the sync runs are for the local machine.
See the Drive an interactive program
example: wait for a line, answer, end of input, timeout and kill.
Platform notes
- Windows built-ins (
echo, dir, type, del) work because they are run
in the shell; prefer dart:io File/Directory for file operations that
must be portable.
- Flutter macOS apps must disable App Sandbox in the entitlements files to
start processes.
sudo on Linux: alias sudo to sudo --stdin and pass
stdin: sharedStdIn so the password prompt works.
Examples
Run a script and read the output
import 'package:process_run/shell.dart';
Future<void> main() async {
var shell = Shell(verbose: false);
var results = await shell.run('''
git rev-parse --abbrev-ref HEAD
git rev-parse HEAD
''');
var branch = results[0].outText.trim();
var commit = results.last.outText.trim();
print('$branch@$commit');
// All lines of all commands
for (var line in results.outLines) {
print(line);
}
}
Arguments from variables, quoting
import 'package:process_run/shell.dart';
Future<void> commit(String message, List<String> files) async {
var shell = Shell();
// Explicit argument list: nothing to quote.
await shell.runExecutableArguments('git', ['add', ...files]);
// Script line: quote what may contain spaces.
await shell.run('git commit -m ${shellArgument(message)}');
// Equivalent using a ShellCommand.
await shell.runCommand(ShellCommand('git', ['commit', '-m', message]));
}
Handle failures
import 'package:process_run/shell.dart';
Future<bool> hasChanges() async {
var shell = Shell(verbose: false, throwOnError: false);
var result = await shell.runExecutableArguments('git', [
'diff',
'--quiet',
]);
return result.exitCode != 0;
}
Future<void> deploy() async {
try {
await run('firebase deploy');
} on ShellException catch (e) {
print('deploy failed: ${e.message}');
print('exit code: ${e.result?.exitCode}');
print(e.toDebugString());
rethrow;
}
}
Working directory, pushd/popd
import 'package:process_run/shell.dart';
Future<void> main() async {
var shell = Shell();
await shell.cd('packages/app').run('dart pub get');
shell = shell.pushd('packages/lib');
await shell.run('dart test');
shell = shell.popd();
print(shell.path); // back to the original directory
}
Multi-line command and comments
import 'package:process_run/shell.dart';
Future<void> main() async {
await run('''
# Build for the web (comment printed only with commentVerbose: true)
dart compile js -o build/main.js \\
--minify \\
web/main.dart
''', commentVerbose: true);
}
Stream lines and stop early
import 'dart:async';
import 'package:process_run/shell.dart';
Future<void> main() async {
var controller = ShellLinesController();
var shell = Shell(stdout: controller.sink, verbose: false);
late StreamSubscription<String> subscription;
subscription = controller.stream.listen((line) {
print('server: $line');
if (line.contains('Serving at')) {
shell.kill();
subscription.cancel();
}
});
try {
await shell.run('dart run dhttpd --port 8080');
} on ShellException catch (_) {
// Thrown because the process was killed.
} finally {
controller.close();
}
}
Feed stdin
import 'package:process_run/shell.dart';
Future<void> main() async {
var input = ShellLinesController();
var shell = Shell(stdin: input.binaryStream, verbose: false);
var done = shell.run('sort');
input.writeln('b');
input.writeln('a');
input.close();
var results = await done;
print(results.outLines.toList()); // [a, b]
}
Drive an interactive program
A test or a tool answering a program: one ShellLinesController for its
stdin, one for its stdout, a timeout killing it when it hangs.
import 'dart:async';
import 'dart:io';
import 'package:process_run/shell.dart';
/// Answers the `name:` prompt of `my_tool` with [name]; null when it hangs.
Future<ProcessResult?> answerName(String name) async {
var input = ShellLinesController();
var output = ShellLinesController();
var shell = Shell(
stdin: input.binaryStream,
stdout: output.sink,
verbose: false,
throwOnError: false,
);
var asked = Completer<void>();
output.stream.listen((line) {
if (line.startsWith('name:') && !asked.isCompleted) {
asked.complete();
}
});
// Not awaited: the program runs while we drive it.
var done = shell.runExecutableArguments('my_tool', ['--ask-name']);
try {
await asked.future.timeout(const Duration(seconds: 15));
input.writeln(name);
// End of input: the program gets done on its stdin.
input.close();
return await done.timeout(const Duration(seconds: 15));
} on TimeoutException catch (_) {
done.ignore(); // A killed run throws a ShellException.
shell.kill(ProcessSignal.sigkill);
return null;
} finally {
input.close();
output.close();
}
}
The result holds the whole output (result.outLines) and the exit code.
package:process_run_test test/shared_stdin_test.dart uses this pattern on
a program reading through sharedStdIn.
Options object, clone, sync run
import 'dart:convert';
import 'package:process_run/shell.dart';
void main() {
var options = ShellOptions(
verbose: false,
throwOnError: false,
stdoutEncoding: utf8,
);
var shell = Shell(options: options);
var quiet = shell.cloneWithOptions(options.clone(commandVerbose: true));
// Synchronous: no stdin, no kill, blocks the isolate.
var result = quiet.runExecutableArgumentsSync('dart', ['--version']);
print('${result.exitCode}: ${result.outText}');
}
Common mistakes
- Writing
cmd1 | cmd2, cmd > file, cd dir or export VAR=1 in a
script: each line must be one executable. Use shell.cd, dart:io files
and Shell(environment: ...) instead.
- Expecting the global
runExecutableArguments to throw on failure or print
output: it is silent and non-throwing by default, unlike run.
- Forgetting to reassign
shell = shell.cd(...) / pushd / popd.
- Using
result.stdout as a List<int>: it is a String unless
stdoutEncoding: null was passed to a ShellOptions.
- Passing
noStdoutResult: true together with a stdout: sink and
expecting the sink to receive the output: the output is dropped.
- Reading
e.result!.exitCode in a ShellException handler: result is
null when the executable was not found or the directory does not exist.
- Using
dart:io Process.start (with its stdin/stdout streams and
exitCode) in a tool or a test: use Shell with two
ShellLinesControllers, see Driving a program.
- Leaving a
ShellLinesController open or never calling
sharedStdIn.terminate(): the program does not exit. Not closing the
stdin controller: a command reading until the end of input never ends.
- Awaiting
prompt / promptConfirm without catching the StateError it
throws at the end of input (stdin a pipe or /dev/null).
- Reusing one
Shell for parallel run calls and expecting concurrency; they
are serialized.
More
See references/api.md for the ShellOptions
parameter table, the result and exception members, ShellCommand, and the
lower level ProcessCmd/runCmd API of package:process_run/cmd_run.dart.
1---2name: process-run-shell3description: >-4 Use when running external commands or multi-line scripts from Dart with5 package:process_run (Shell, run, runSync, runExecutableArguments,6 runExecutableArgumentsSync, ShellOptions, ShellException, ShellCommand,7 runCommand, runScript, outText/outLines/errText/errLines, verbose,8 commandVerbose, throwOnError, workingDirectory, cd/pushd/popd,9 shellArgument/shellArguments quoting, stdout/stderr sinks,10 ShellLinesController, stdin, sharedStdIn, prompt, kill, onProcess,11 noStdoutResult), and instead of dart:io Process.start / Process.run, tests12 included: driving a program (feed its stdin, wait for an output line,13 answer, end of input, timeout and kill). Covers script syntax, executable14 resolution, result capture and error handling on Linux, macOS and Windows.15metadata:16 source: https://skillmd.com/skills/tekartik/process-run-shell17---1819# process_run shell: run commands portably2021`package:process_run/shell.dart` runs one or many command lines from Dart on22Linux, macOS and Windows with the same script text. Each line is one23executable resolved with `which` semantics, started through `dart:io`24`Process` and returned as a `ProcessResult`. VM only (`dart:io`): Dart CLI25and Flutter desktop/mobile, not web.2627```dart28import 'package:process_run/shell.dart';2930Future<void> main() async {31 var shell = Shell();32 await shell.run('''33# Comments are allowed34dart --version35git status36''');37}38```3940## Guidelines4142### Choosing the entry point4344* Start every process through process_run, tests included, never with45 `dart:io` `Process.start` / `Process.run`: same executable resolution,46 quoting and output capture everywhere, and `kill()` stops the whole47 process tree. Each raw `Process` piece has a `Shell` equivalent, see48 [Driving a program](#driving-a-program-instead-of-processstart).49* `Shell()` then `shell.run(script)` is the primary API. Use the global50 `run(script)` for one-off calls; it builds a `Shell` with the same51 parameters. Both default to `verbose: true` (command echoed, stdout and52 stderr streamed to the terminal) and `throwOnError: true`.53* `shell.runExecutableArguments(executable, arguments)` runs one command from54 an explicit argument list (no quoting/splitting), with the shell options.55 Prefer it over string building when arguments come from variables.56* The **global** `runExecutableArguments(...)` and57 `runExecutableArgumentsSync(...)` (also in `shell.dart`) default to58 `verbose: false` and `throwOnError: false`, unlike `run`. Check `exitCode`59 yourself or pass `throwOnError: true`.60* `runSync` / `runExecutableArgumentsSync` (global and on `Shell`) block until61 the child exits, cannot receive `stdin`, cannot be `kill()`ed and ignore62 `noStdoutResult`/`noStderrResult`. Use them in tests and tiny scripts only.63* A `Shell` is immutable: `cd`, `pushd`, `popd`, `cloneWithOptions` return a64 new `Shell`. `shell.options` exposes the `ShellOptions` in use and65 `shell.options.clone(...)` derives a modified copy.66* `Shell(options: ShellOptions(...))` overrides every other constructor67 parameter. Keep one `ShellOptions` when you create many shells.6869### Script syntax (`run`, `runSync`, `runScript`)7071* One command per line. Lines are trimmed; empty lines are ignored; lines72 starting with `#`, `// ` or `/// ` are comments (printed only with73 `commentVerbose: true`).74* A line ending with ` ^` or ` \` (space then the character; in a Dart75 string write `' '`) continues on the next line.76* No pipes, redirections, `&&`, variables or loops: each line is exactly one77 executable plus arguments. Do that logic in Dart.78* The first word is the executable. A plain name is searched in the shell79 environment paths (`PATH` plus user config paths and the running dart SDK80 `bin` directory) and aliases; a relative path is resolved from81 `workingDirectory`; an absolute path is used as is. On Windows the82 `PATHEXT` extensions (`.exe`, `.bat`, `.cmd`...) are tried.83* Quote arguments containing spaces with double or single quotes, or build the84 line with `shellArgument(value)` / `shellArguments(list)`. On Windows the85 backslash is not an escape character (`C:\dir` is fine); on Linux/macOS a86 bare backslash escapes the next character, so use `shellArgument` for paths87 with backslashes.88* `ShellCommand.parse(line)` and `ShellCommand(executable, arguments)`89 build a single command object; `shell.runCommand(command)` runs it and90 returns a `ShellProcessResult`. `shellScriptSplitLines(script)` and91 `shellScriptLineToArguments(line)` expose the parser.92* Leave `runInShell` null. It defaults to false, except on Windows where any93 executable without a `.exe` extension (built-ins like `echo`, `.bat`94 scripts) is run through the shell automatically.9596### Output and results9798* `run` returns `List<ProcessResult>` (one per command, in order). Import of99 `shell.dart` adds `outText`, `errText`, `outLines`, `errLines` on the list100 (all commands concatenated) and on each `ProcessResult`. `outText` joins101 lines with `\n` and has no trailing newline; `result.stdout` is the raw102 `String` decoded with `stdoutEncoding`.103* `shell.runScript(script)` returns `ShellProcessResults`104 (a `List<ShellProcessResult>`) with the same helpers plus105 `stdoutAsString`, `stderrAsString`, `stdoutAsUint8List`,106 `stderrAsUint8List` and `processResults` (the raw list). Prefer it when you107 need the exact bytes or the executed `command`.108* `verbose: false` captures silently; output is still available in the109 results. `commandVerbose: true` with `verbose: false` prints only the110 `$ command` line.111* Pass `stdout:` / `stderr:` (`StreamSink<List<int>>`) to receive the child112 output as it is produced (with `verbose: true` it goes to the sink instead113 of the terminal). Use `ShellLinesController` to get a `Stream<String>` of114 lines: `Shell(stdout: controller.sink)`, listen to `controller.stream`,115 `controller.close()` when done.116* Output is always buffered in the result. For a command whose output you117 do not need at all, `ShellOptions(noStdoutResult: true)` /118 `noStderrResult: true` (or the same named parameters of the global119 `runExecutableArguments`) discard it: the result field is null and120 nothing is streamed to the terminal or to the sinks either. Ignored by121 the sync variants.122* Default encoding is `systemEncoding`. Pass `stdoutEncoding: utf8` (and123 `stderrEncoding`) when the tool prints UTF-8 on Windows.124* `ShellOptions(mode: ProcessStartMode.inheritStdio)` hands the terminal to125 the child (interactive tools); nothing is captured in that mode.126* `ShellOptions(mode: ProcessStartMode.detached)` starts a program that127 lives on after yours (an editor, a browser, another window): the run ends128 once it started, exit code 0 (it has none), no output, and `kill()` leaves129 it. With `detachedWithStdio` its pipes are the ones of the process given130 to `onProcess`, the shell reads nothing (since 1.4.4, it threw before).131* A `stdout:`/`stderr:` sink can be closed while the command still writes132 (after a `kill()`, it takes time to end): it gets nothing more.133* `ShellLinesController` never drops a line: one that is not in its134 encoding is read as UTF-8 with U+FFFD for what is not text. The result of135 a run is decoded strictly (`FormatException` on a tool printing bytes):136 pass `stdoutEncoding: const Utf8Codec(allowMalformed: true)` for such a137 tool.138139### Errors140141* With `throwOnError: true` (default) a non-zero exit code throws142 `ShellException`. Catch it: `e.message`, `e.shellCommand` (the parsed143 command), `e.result` (`ProcessResult?`, null when the executable could not144 be started), `e.shellProcessResult`, and `e.toDebugString()` (message,145 directory, command, exit code, out and err).146* A missing executable or a missing `workingDirectory` also throws147 `ShellException` (wrapping the `ProcessException`) with `result == null`.148* Use `Shell(throwOnError: false)` when a non-zero exit code is expected149 (`grep`, `lsof`, `git diff --exit-code`) and read `result.exitCode`.150* `run` executes the script sequentially and stops at the first failing151 command when `throwOnError` is true; the results of the earlier commands152 are lost (only the exception is returned). Split the script if you need153 partial results.154* Never build a `ShellException` yourself; the factory constructors are for155 the package.156157### Working directory158159* `Shell(workingDirectory: path)` or `shell.cd(path)`. A relative `cd` path is160 resolved against the current shell directory. `shell.path` returns the161 effective directory.162* `shell = shell.pushd('sub')` then `shell = shell.popd()` mimic the shell163 builtins; `popd()` throws `StateError` when there is nothing to pop. Always164 reassign the returned shell.165* Relative script paths (`dart tool/build.dart`) are relative to the shell166 `workingDirectory`, not to the Dart process directory.167168### stdin, long running processes and kill169170* Feed input with `Shell(stdin: stream)` where the stream is a171 `Stream<List<int>>`. To feed generated text use a `ShellLinesController`:172 `Shell(stdin: input.binaryStream)`, `input.write('...')` /173 `input.writeln('...')` (also after the run started, e.g. once the program174 printed a prompt), `input.close()`. Closing it is the end of input of the175 command: one reading its input until the end (`cat`, `sort`) only exits176 then.177* `ShellLinesController` works both ways: as `stdout:` / `stderr:` (give178 its `sink`, listen to its `stream` of lines) and as `stdin:` (write to it,179 give its `binaryStream`). One controller per direction.180* To forward the user's terminal input use `sharedStdIn` (the program's own181 stdin, shareable by several commands and prompts in turn) and call182 `await sharedStdIn.terminate()` before the program ends (otherwise it183 never exits). At the end of its input (a pipe, `< /dev/null`, CI),184 `sharedStdIn` listeners get done: `lines()` completes, a command given185 `stdin: sharedStdIn` gets its end of input, and `prompt`,186 `promptConfirm` and `nextLine` throw a `StateError` (no element): catch it187 in a tool that may run without a terminal.188* `shell.kill()` kills the running command and all its descendant189 processes (children, grandchildren...): `sigterm`, then `sigkill` for the190 ones still running after 5 s (`taskkill /t /f` on Windows); the pending191 `run` future completes with `ShellException`. Prefer it: servers such as192 `dhttpd` and `flutter test` (its browser) leave processes behind otherwise.193 `shell.kill(signal)` sends `signal` to the command only (`sigint` to stop194 the Firebase emulators), except `ProcessSignal.sigkill` which kills the195 descendants too.196* Any process, by pid (an app started from elsewhere, a process tree):197 `ShellProcesses.findByExecutable(path)`, `ShellProcesses.descendantsOf(pid)`,198 `ShellProcesses.isRunning(pid)` and `ShellProcesses.kill(pids, tree: true)`199 (sigterm, sigkill after `timeout`, 5 s by default; returns the ones still200 running).201* `run(script, onProcess: (process) {...})` gives the `dart:io` `Process`202 of each command as it starts (pid, manual kill).203* Calls on one `Shell` are serialized with a lock: two concurrent204 `shell.run` on the same instance execute one after the other. Create205 distinct shells for parallel work.206207### Driving a program (instead of Process.start)208209| `dart:io` `Process` | process_run |210|---|---|211| `Process.start(exe, args)` | `shell.runExecutableArguments(exe, args)`: a future of the result, do not await it before driving the program |212| `process.stdin.write(...)`, `.close()` | `ShellLinesController` input: `Shell(stdin: input.binaryStream)`, `input.write(...)`, `input.close()` (end of input) |213| `process.stdout` lines | `ShellLinesController` output: `Shell(stdout: output.sink)`, `output.stream` |214| `await process.exitCode` | `(await done).exitCode`, with `throwOnError: false` |215| all the output after exit | `result.outLines` / `outText`: still captured with a `stdout:` sink |216| `process.kill()` | `shell.kill()` (the whole tree; the run then throws `ShellException`, at once) |217| `process.kill()` then `await process.exitCode` | with the process of `onProcess`: `process.kill()` (the command only) or `await ShellProcesses.kill([process.pid], tree: true)` (what it started too); the run then ends as the command does, `(await done).exitCode` |218| `process.pid`, `process.exitCode` at exit | `onProcess: (process) { ... }`: the result of the run comes later, with the end of the output (a process left behind holds it) |219| `Process.run(exe, args)` | `Shell(verbose: false, throwOnError: false).runExecutableArguments(exe, args)`; `Process.run` ends the input of the command, a shell leaves it open: add `stdin: const Stream.empty()` for a command reading it |220| `Process.start(..., mode: ProcessStartMode.detached)` | `ShellOptions(mode: ProcessStartMode.detached)`: the run ends once started |221| `Process.killPid(pid)` | `ShellProcesses.kill([pid])` |222223Code meant to run on another shell context too (a remote shell, a web app)224keeps to `Shell`, its sinks, `kill()` and the process of `onProcess` (pid,225exit code, kill), and asks the context for the rest: `shellContext`226(`package:process_run/utils/shell_context.dart`) has `which`, `platform`,227`path` and `shellEnvironment`. The global `which`/`whichSync`,228`ShellProcesses`, `sharedStdIn` and the sync runs are for the local machine.229230See the [Drive an interactive program](#drive-an-interactive-program)231example: wait for a line, answer, end of input, timeout and kill.232233### Platform notes234235* Windows built-ins (`echo`, `dir`, `type`, `del`) work because they are run236 in the shell; prefer `dart:io` `File`/`Directory` for file operations that237 must be portable.238* Flutter macOS apps must disable App Sandbox in the entitlements files to239 start processes.240* `sudo` on Linux: alias `sudo` to `sudo --stdin` and pass241 `stdin: sharedStdIn` so the password prompt works.242243## Examples244245### Run a script and read the output246247```dart248import 'package:process_run/shell.dart';249250Future<void> main() async {251 var shell = Shell(verbose: false);252 var results = await shell.run('''253git rev-parse --abbrev-ref HEAD254git rev-parse HEAD255''');256 var branch = results[0].outText.trim();257 var commit = results.last.outText.trim();258 print('$branch@$commit');259260 // All lines of all commands261 for (var line in results.outLines) {262 print(line);263 }264}265```266267### Arguments from variables, quoting268269```dart270import 'package:process_run/shell.dart';271272Future<void> commit(String message, List<String> files) async {273 var shell = Shell();274 // Explicit argument list: nothing to quote.275 await shell.runExecutableArguments('git', ['add', ...files]);276 // Script line: quote what may contain spaces.277 await shell.run('git commit -m ${shellArgument(message)}');278 // Equivalent using a ShellCommand.279 await shell.runCommand(ShellCommand('git', ['commit', '-m', message]));280}281```282283### Handle failures284285```dart286import 'package:process_run/shell.dart';287288Future<bool> hasChanges() async {289 var shell = Shell(verbose: false, throwOnError: false);290 var result = await shell.runExecutableArguments('git', [291 'diff',292 '--quiet',293 ]);294 return result.exitCode != 0;295}296297Future<void> deploy() async {298 try {299 await run('firebase deploy');300 } on ShellException catch (e) {301 print('deploy failed: ${e.message}');302 print('exit code: ${e.result?.exitCode}');303 print(e.toDebugString());304 rethrow;305 }306}307```308309### Working directory, pushd/popd310311```dart312import 'package:process_run/shell.dart';313314Future<void> main() async {315 var shell = Shell();316 await shell.cd('packages/app').run('dart pub get');317318 shell = shell.pushd('packages/lib');319 await shell.run('dart test');320 shell = shell.popd();321 print(shell.path); // back to the original directory322}323```324325### Multi-line command and comments326327```dart328import 'package:process_run/shell.dart';329330Future<void> main() async {331 await run('''332# Build for the web (comment printed only with commentVerbose: true)333dart compile js -o build/main.js \\334 --minify \\335 web/main.dart336''', commentVerbose: true);337}338```339340### Stream lines and stop early341342```dart343import 'dart:async';344345import 'package:process_run/shell.dart';346347Future<void> main() async {348 var controller = ShellLinesController();349 var shell = Shell(stdout: controller.sink, verbose: false);350 late StreamSubscription<String> subscription;351 subscription = controller.stream.listen((line) {352 print('server: $line');353 if (line.contains('Serving at')) {354 shell.kill();355 subscription.cancel();356 }357 });358 try {359 await shell.run('dart run dhttpd --port 8080');360 } on ShellException catch (_) {361 // Thrown because the process was killed.362 } finally {363 controller.close();364 }365}366```367368### Feed stdin369370```dart371import 'package:process_run/shell.dart';372373Future<void> main() async {374 var input = ShellLinesController();375 var shell = Shell(stdin: input.binaryStream, verbose: false);376 var done = shell.run('sort');377 input.writeln('b');378 input.writeln('a');379 input.close();380 var results = await done;381 print(results.outLines.toList()); // [a, b]382}383```384385### Drive an interactive program386387A test or a tool answering a program: one `ShellLinesController` for its388stdin, one for its stdout, a timeout killing it when it hangs.389390```dart391import 'dart:async';392import 'dart:io';393394import 'package:process_run/shell.dart';395396/// Answers the `name:` prompt of `my_tool` with [name]; null when it hangs.397Future<ProcessResult?> answerName(String name) async {398 var input = ShellLinesController();399 var output = ShellLinesController();400 var shell = Shell(401 stdin: input.binaryStream,402 stdout: output.sink,403 verbose: false,404 throwOnError: false,405 );406 var asked = Completer<void>();407 output.stream.listen((line) {408 if (line.startsWith('name:') && !asked.isCompleted) {409 asked.complete();410 }411 });412 // Not awaited: the program runs while we drive it.413 var done = shell.runExecutableArguments('my_tool', ['--ask-name']);414 try {415 await asked.future.timeout(const Duration(seconds: 15));416 input.writeln(name);417 // End of input: the program gets done on its stdin.418 input.close();419 return await done.timeout(const Duration(seconds: 15));420 } on TimeoutException catch (_) {421 done.ignore(); // A killed run throws a ShellException.422 shell.kill(ProcessSignal.sigkill);423 return null;424 } finally {425 input.close();426 output.close();427 }428}429```430431The result holds the whole output (`result.outLines`) and the exit code.432`package:process_run_test` `test/shared_stdin_test.dart` uses this pattern on433a program reading through `sharedStdIn`.434435### Options object, clone, sync run436437```dart438import 'dart:convert';439440import 'package:process_run/shell.dart';441442void main() {443 var options = ShellOptions(444 verbose: false,445 throwOnError: false,446 stdoutEncoding: utf8,447 );448 var shell = Shell(options: options);449 var quiet = shell.cloneWithOptions(options.clone(commandVerbose: true));450451 // Synchronous: no stdin, no kill, blocks the isolate.452 var result = quiet.runExecutableArgumentsSync('dart', ['--version']);453 print('${result.exitCode}: ${result.outText}');454}455```456457## Common mistakes458459* Writing `cmd1 | cmd2`, `cmd > file`, `cd dir` or `export VAR=1` in a460 script: each line must be one executable. Use `shell.cd`, `dart:io` files461 and `Shell(environment: ...)` instead.462* Expecting the global `runExecutableArguments` to throw on failure or print463 output: it is silent and non-throwing by default, unlike `run`.464* Forgetting to reassign `shell = shell.cd(...)` / `pushd` / `popd`.465* Using `result.stdout` as a `List<int>`: it is a `String` unless466 `stdoutEncoding: null` was passed to a `ShellOptions`.467* Passing `noStdoutResult: true` together with a `stdout:` sink and468 expecting the sink to receive the output: the output is dropped.469* Reading `e.result!.exitCode` in a `ShellException` handler: `result` is470 null when the executable was not found or the directory does not exist.471* Using `dart:io` `Process.start` (with its `stdin`/`stdout` streams and472 `exitCode`) in a tool or a test: use `Shell` with two473 `ShellLinesController`s, see Driving a program.474* Leaving a `ShellLinesController` open or never calling475 `sharedStdIn.terminate()`: the program does not exit. Not closing the476 stdin controller: a command reading until the end of input never ends.477* Awaiting `prompt` / `promptConfirm` without catching the `StateError` it478 throws at the end of input (stdin a pipe or `/dev/null`).479* Reusing one `Shell` for parallel `run` calls and expecting concurrency; they480 are serialized.481482## More483484See [references/api.md](references/api.md) for the `ShellOptions`485parameter table, the result and exception members, `ShellCommand`, and the486lower level `ProcessCmd`/`runCmd` API of `package:process_run/cmd_run.dart`.