process_run environment: variables, paths and aliases
package:process_run/shell.dart gives every Shell a ShellEnvironment:
the environment variables of the child processes, the list of directories
used to resolve executables (PATH) and command aliases. The default one is
the process environment plus what the user configured in env.yaml files,
so a script finds flutter or firebase even when the IDE did not export
the right PATH.
import 'package:process_run/shell.dart';
Future<void> main() async {
var env = ShellEnvironment()
..vars['CI'] = 'true'
..paths.prepend('/opt/flutter/bin')
..aliases['ll'] = 'ls -l';
var shell = Shell(environment: env);
await shell.run('flutter --version');
await shell.run('ll');
}
Guidelines
ShellEnvironment
ShellEnvironment() copies the current shell environment (process
variables, user config vars, paths and aliases, and the running dart SDK
bin directory prepended to the paths). ShellEnvironment.empty() starts
from nothing. ShellEnvironment(environment: map) copies a plain map
(its PATH becomes paths); passing a ShellEnvironment also copies its
aliases.
- It is a
Map<String, String> (the variables including PATH) with three
views:
vars (a Map<String, String> of every variable except PATH),
paths (a List<String> view of PATH: prepend, add, addAll,
insert, remove; duplicates are dropped) and
aliases (a Map<String, String> of name to command line).
env.merge(other): other wins for vars and aliases, its paths are
prepended. env.whichSync(name) / await env.which(name) resolve an
executable in that environment only. toJson() / ShellEnvironment.fromJson
give {'paths': [...], 'vars': {...}, 'aliases': {...}}.
- Treat an environment as immutable once given to a
Shell: the shell copies
it into its options. Build a new one (or ShellEnvironment(environment: old))
for changes.
Applying it to a shell
Shell(environment: env) with the default includeParentEnvironment: true
merges env on top of the full current environment (vars override, paths
prepended, aliases added). Pass a small ShellEnvironment or a plain
Map<String, String> with only the additions.
Shell(environment: env, includeParentEnvironment: false) gives the child
exactly env: you then own PATH, HOME, TEMP etc. Use it for
reproducible builds or tests, and put the needed paths in env.paths.
shell.options.environment is the effective ShellEnvironment of a shell.
shell.cloneWithOptions(shell.options.clone(shellEnvironment: env))
derives a shell with another environment; cd/pushd keep it.
- The global
shellEnvironment getter returns the environment used by every
new Shell()/run(); assigning it (shellEnvironment = env) changes all
subsequent shells in the process and shellEnvironment = null restores the
user config. Prefer per-shell environments; use the global only in a CLI
entry point.
platformEnvironment is Platform.environment without DART_VM_OPTIONS
(replaced by TEKARTIK_DART_VM_OPTIONS when set): use it instead of
Platform.environment when a Dart child must not inherit debugger options.
await env.runZoned(() async { ... }) makes env the default environment
inside the callback (for Shell(), run(), ShellEnvironment(), which)
without touching the global. Zones are isolated from each other, so
concurrent zones can use different values.
Executable and alias resolution
- The first word of a command line is looked up, in order: the shell
environment aliases (nested aliases allowed, each expanded once, alias
arguments prepended: with
qr: my_app --verbose, qr file.png runs
my_app --verbose file.png), then the executable in paths.
- Last resort on Linux/macOS: when nothing is found, the user shell
(
$SHELL: bash, zsh, sh, dash, ash, ksh; not fish) is asked for an alias
of that name (alias ll='ls -alF' in ~/.bashrc/~/.zshrc). Turn it off
with userShellAliasEnabled = false, force a shell with
userShellAliasShellPathOverride = '/bin/zsh'; userShellAliasShellPath
tells which shell will be used, userShellAliasSupportedShells lists the
supported names. It spawns an interactive shell (slow, cached per
process) and only triggers on commands that would fail anyway.
- Aliases are the portable way to name a tool whose location differs per
machine (
env.aliases['echo'] = compiledEchoPath in tests, ds to
dart run bin/shell.dart in development).
User configuration files (env.yaml)
- User file:
~/.config/tekartik/process_run/env.yaml on Linux/macOS,
%APPDATA%\tekartik\process_run\env.yaml on Windows. Local file:
.local/ds_env.yaml in the current directory, applied after the user file
(it wins). Both are read once per process when the first shell environment
is built.
- YAML keys:
path (or paths, a list or a single string, ~ expanded),
var (or vars, a map) and alias (or aliases, a map). The paths are
prepended to PATH, the vars override the process ones.
- Override the locations with the environment variables
TEKARTIK_PROCESS_RUN_USER_ENV_FILE_PATH (absolute user file),
TEKARTIK_PROCESS_RUN_LOCAL_ENV_FILE_PATH (relative local file),
TEKARTIK_PROCESS_RUN_USER_HOME_PATH and
TEKARTIK_PROCESS_RUN_USER_APP_DATA_PATH. Set them in tests to keep the
developer files untouched.
userEnvironment (a Map<String, String>) and userPaths
(List<String>) expose the merged result; userLoadEnvFile(path) and
userLoadEnv(vars: {...}, paths: [...]) add vars and paths to it for the
whole process (aliases passed to userLoadEnv are not applied). Prefer
a ShellEnvironment per shell.
await shell.shellVarOverride('NAME', 'value') writes the variable in the
local file (local: false for the user file), null deletes it, and
returns a new Shell whose environment has the change.
- Keep secrets in the user file
var: section rather than in code; they are
in userEnvironment and in every ShellEnvironment().
The ds command line
- Install with
dart install process_run (Dart 3.10+, executable ds) or
dart pub global activate process_run (legacy), or run it in a project
with dart run process_run:ds <args> (process_run:shell with older
versions).
ds run <command...>: run one command line with the process_run
environment (aliases, paths, vars). ds run --info <command> dumps the
files, vars, paths and aliases used.
ds env var set NAME value words / get NAME / dump / delete NAME;
ds env path prepend <dir...> / get <dir...> / dump / delete <dir...>;
ds env alias set NAME command words / get NAME / dump /
delete NAME. Values can span several arguments, they are joined with
spaces.
- Every
env command edits the local file by default (-l, --local);
add -u / --user for the user file. ds env edit opens the file in an
editor, ds env info and ds env --info print the files, ds env delete
(-f to skip the prompt) removes the file.
- In a Dart script that must call
ds, alias it:
ShellEnvironment()..aliases['ds'] = 'dart run process_run:shell'.
Examples
Add a tool directory and a variable for one shell
import 'package:process_run/shell.dart';
Future<void> main() async {
var env = ShellEnvironment()
..paths.prepend('/opt/android/platform-tools')
..vars['ANDROID_SERIAL'] = 'emulator-5554';
var shell = Shell(environment: env, verbose: false);
var devices = await shell.run('adb devices');
print(devices.outText);
}
Minimal, fully controlled environment
import 'package:process_run/shell.dart';
Future<void> main() async {
var env = ShellEnvironment.empty()
..paths.addAll(['/usr/bin', '/bin'])
..vars['HOME'] = '/tmp/build-home'
..vars['LANG'] = 'C';
var shell = Shell(environment: env, includeParentEnvironment: false);
await shell.run('env');
}
Aliases, including nested ones
import 'package:process_run/shell.dart';
Future<void> main() async {
var env = ShellEnvironment()
..aliases['fvm_flutter'] = 'fvm flutter'
..aliases['fbuild'] = 'fvm_flutter build';
var shell = Shell(environment: env);
// Runs `fvm flutter build apk --release`.
await shell.run('fbuild apk --release');
}
Check a tool from a given environment
import 'package:process_run/shell.dart';
bool hasFirebaseCli(ShellEnvironment env) => env.whichSync('firebase') != null;
Future<void> main() async {
var env = ShellEnvironment()..paths.prepend('/home/me/.firebase/tools/bin');
if (!hasFirebaseCli(env)) {
print('firebase not found in ${env.paths}');
return;
}
await Shell(environment: env).run('firebase --version');
}
Scoped default environment with runZoned
import 'package:process_run/shell.dart';
Future<void> buildFlavor(String flavor) => (ShellEnvironment()
..vars['FLAVOR'] = flavor)
.runZoned(() async {
// Every Shell()/run() created here sees FLAVOR=flavor.
await run('dart run tool/build.dart');
});
Future<void> main() async {
await Future.wait([buildFlavor('dev'), buildFlavor('prod')]);
}
Persist a variable in the local env.yaml
import 'package:process_run/shell.dart';
Future<void> main() async {
var shell = Shell(verbose: false);
// Written to .local/ds_env.yaml, picked up by every future `ds run`
// and `Shell()` in this directory.
shell = await shell.shellVarOverride('MY_PROJECT_ID', 'proj-123');
print(shell.options.environment.vars['MY_PROJECT_ID']); // proj-123
// Delete it.
shell = await shell.shellVarOverride('MY_PROJECT_ID', null);
}
Sample ~/.config/tekartik/process_run/env.yaml
path:
- ~/.android/bin
- ~/.firebase/tools/bin
- /home/user/Apps/bin
var:
ANDROID_TOP: ~/.android
MY_PROJECT_ID: WKDL_456_Q
alias:
qr: /path/to/my_qr_app
hello: echo Hello
Redirect the config files in tests
import 'package:process_run/shell.dart';
import 'package:test/test.dart';
void main() {
test('isolated env files', () async {
var env = ShellEnvironment()
..vars['TEKARTIK_PROCESS_RUN_USER_ENV_FILE_PATH'] =
'.dart_tool/test/user_env.yaml'
..vars['TEKARTIK_PROCESS_RUN_LOCAL_ENV_FILE_PATH'] =
'.dart_tool/test/local_env.yaml'
..aliases['ds'] = 'dart run process_run:shell';
var shell = Shell(environment: env, verbose: false);
await shell.run('ds env var set TEST_VAR 1');
var out = (await shell.run('ds env var get TEST_VAR')).outText;
expect(out, contains('TEST_VAR: 1'));
});
}
Common mistakes
env.vars['PATH'] = ...: ignored, PATH is only editable through
env.paths.
- Mutating a
ShellEnvironment after creating the Shell and expecting the
shell to see it: create a new shell (cloneWithOptions) instead.
includeParentEnvironment: false with an environment that has no paths:
no executable can be resolved and the child has no PATH.
- Assigning the global
shellEnvironment in a library: it leaks into every
shell of the application. Use Shell(environment:) or runZoned.
- Expecting
alias entries added with userLoadEnv(aliases:) to work: only
vars and paths are applied; use ShellEnvironment.aliases or the
env.yaml alias: section.
- Expecting
ds env var set to affect the current shell object: it edits
the file; use shellVarOverride or create a new Shell afterwards.
- Running
ds on Windows/Linux without dart pub global activate process_run or the dart run process_run:shell prefix.
More
See references/ds-cli.md for the full ds command
tree, the env.yaml format details and the lower level helpers
(getUserEnvFilePath, getLocalEnvFilePath, userConfig).
1---2name: process-run-environment3description: >-4 Use when configuring the environment of commands run with5 package:process_run: ShellEnvironment (vars, paths, aliases, merge,6 prepend, whichSync), Shell(environment:), includeParentEnvironment, the7 global shellEnvironment and platformEnvironment, userEnvironment/userPaths,8 the user and local env.yaml files (~/.config/tekartik/process_run/env.yaml,9 .local/ds_env.yaml), userLoadEnv/userLoadEnvFile, alias resolution and the10 user shell alias fallback (userShellAliasEnabled), ShellEnvironment.runZoned,11 shellVarOverride, and the ds command line (dart run process_run:shell env12 var/path/alias set|get|dump|delete, ds run, ds env edit).13metadata:14 source: https://skillmd.com/skills/tekartik/process-run-environment15---1617# process_run environment: variables, paths and aliases1819`package:process_run/shell.dart` gives every `Shell` a `ShellEnvironment`:20the environment variables of the child processes, the list of directories21used to resolve executables (`PATH`) and command aliases. The default one is22the process environment plus what the user configured in `env.yaml` files,23so a script finds `flutter` or `firebase` even when the IDE did not export24the right `PATH`.2526```dart27import 'package:process_run/shell.dart';2829Future<void> main() async {30 var env = ShellEnvironment()31 ..vars['CI'] = 'true'32 ..paths.prepend('/opt/flutter/bin')33 ..aliases['ll'] = 'ls -l';34 var shell = Shell(environment: env);35 await shell.run('flutter --version');36 await shell.run('ll');37}38```3940## Guidelines4142### ShellEnvironment4344* `ShellEnvironment()` copies the current shell environment (process45 variables, user config vars, paths and aliases, and the running dart SDK46 `bin` directory prepended to the paths). `ShellEnvironment.empty()` starts47 from nothing. `ShellEnvironment(environment: map)` copies a plain map48 (its `PATH` becomes `paths`); passing a `ShellEnvironment` also copies its49 aliases.50* It is a `Map<String, String>` (the variables including `PATH`) with three51 views:52 `vars` (a `Map<String, String>` of every variable except `PATH`),53 `paths` (a `List<String>` view of `PATH`: `prepend`, `add`, `addAll`,54 `insert`, `remove`; duplicates are dropped) and55 `aliases` (a `Map<String, String>` of name to command line).56* `env.merge(other)`: `other` wins for vars and aliases, its paths are57 prepended. `env.whichSync(name)` / `await env.which(name)` resolve an58 executable in that environment only. `toJson()` / `ShellEnvironment.fromJson`59 give `{'paths': [...], 'vars': {...}, 'aliases': {...}}`.60* Treat an environment as immutable once given to a `Shell`: the shell copies61 it into its options. Build a new one (or `ShellEnvironment(environment: old)`)62 for changes.6364### Applying it to a shell6566* `Shell(environment: env)` with the default `includeParentEnvironment: true`67 merges `env` on top of the full current environment (vars override, paths68 prepended, aliases added). Pass a small `ShellEnvironment` or a plain69 `Map<String, String>` with only the additions.70* `Shell(environment: env, includeParentEnvironment: false)` gives the child71 exactly `env`: you then own `PATH`, `HOME`, `TEMP` etc. Use it for72 reproducible builds or tests, and put the needed paths in `env.paths`.73* `shell.options.environment` is the effective `ShellEnvironment` of a shell.74 `shell.cloneWithOptions(shell.options.clone(shellEnvironment: env))`75 derives a shell with another environment; `cd`/`pushd` keep it.76* The global `shellEnvironment` getter returns the environment used by every77 new `Shell()`/`run()`; assigning it (`shellEnvironment = env`) changes all78 subsequent shells in the process and `shellEnvironment = null` restores the79 user config. Prefer per-shell environments; use the global only in a CLI80 entry point.81* `platformEnvironment` is `Platform.environment` without `DART_VM_OPTIONS`82 (replaced by `TEKARTIK_DART_VM_OPTIONS` when set): use it instead of83 `Platform.environment` when a Dart child must not inherit debugger options.84* `await env.runZoned(() async { ... })` makes `env` the default environment85 inside the callback (for `Shell()`, `run()`, `ShellEnvironment()`, `which`)86 without touching the global. Zones are isolated from each other, so87 concurrent zones can use different values.8889### Executable and alias resolution9091* The first word of a command line is looked up, in order: the shell92 environment aliases (nested aliases allowed, each expanded once, alias93 arguments prepended: with `qr: my_app --verbose`, `qr file.png` runs94 `my_app --verbose file.png`), then the executable in `paths`.95* Last resort on Linux/macOS: when nothing is found, the user shell96 (`$SHELL`: bash, zsh, sh, dash, ash, ksh; not fish) is asked for an alias97 of that name (`alias ll='ls -alF'` in `~/.bashrc`/`~/.zshrc`). Turn it off98 with `userShellAliasEnabled = false`, force a shell with99 `userShellAliasShellPathOverride = '/bin/zsh'`; `userShellAliasShellPath`100 tells which shell will be used, `userShellAliasSupportedShells` lists the101 supported names. It spawns an interactive shell (slow, cached per102 process) and only triggers on commands that would fail anyway.103* Aliases are the portable way to name a tool whose location differs per104 machine (`env.aliases['echo'] = compiledEchoPath` in tests, `ds` to105 `dart run bin/shell.dart` in development).106107### User configuration files (`env.yaml`)108109* User file: `~/.config/tekartik/process_run/env.yaml` on Linux/macOS,110 `%APPDATA%\tekartik\process_run\env.yaml` on Windows. Local file:111 `.local/ds_env.yaml` in the current directory, applied after the user file112 (it wins). Both are read once per process when the first shell environment113 is built.114* YAML keys: `path` (or `paths`, a list or a single string, `~` expanded),115 `var` (or `vars`, a map) and `alias` (or `aliases`, a map). The paths are116 prepended to `PATH`, the vars override the process ones.117* Override the locations with the environment variables118 `TEKARTIK_PROCESS_RUN_USER_ENV_FILE_PATH` (absolute user file),119 `TEKARTIK_PROCESS_RUN_LOCAL_ENV_FILE_PATH` (relative local file),120 `TEKARTIK_PROCESS_RUN_USER_HOME_PATH` and121 `TEKARTIK_PROCESS_RUN_USER_APP_DATA_PATH`. Set them in tests to keep the122 developer files untouched.123* `userEnvironment` (a `Map<String, String>`) and `userPaths`124 (`List<String>`) expose the merged result; `userLoadEnvFile(path)` and125 `userLoadEnv(vars: {...}, paths: [...])` add vars and paths to it for the126 whole process (aliases passed to `userLoadEnv` are not applied). Prefer127 a `ShellEnvironment` per shell.128* `await shell.shellVarOverride('NAME', 'value')` writes the variable in the129 local file (`local: false` for the user file), `null` deletes it, and130 returns a new `Shell` whose environment has the change.131* Keep secrets in the user file `var:` section rather than in code; they are132 in `userEnvironment` and in every `ShellEnvironment()`.133134### The `ds` command line135136* Install with `dart install process_run` (Dart 3.10+, executable `ds`) or137 `dart pub global activate process_run` (legacy), or run it in a project138 with `dart run process_run:ds <args>` (`process_run:shell` with older139 versions).140* `ds run <command...>`: run one command line with the process_run141 environment (aliases, paths, vars). `ds run --info <command>` dumps the142 files, vars, paths and aliases used.143* `ds env var set NAME value words` / `get NAME` / `dump` / `delete NAME`;144 `ds env path prepend <dir...>` / `get <dir...>` / `dump` / `delete <dir...>`;145 `ds env alias set NAME command words` / `get NAME` / `dump` /146 `delete NAME`. Values can span several arguments, they are joined with147 spaces.148* Every `env` command edits the local file by default (`-l`, `--local`);149 add `-u` / `--user` for the user file. `ds env edit` opens the file in an150 editor, `ds env info` and `ds env --info` print the files, `ds env delete`151 (`-f` to skip the prompt) removes the file.152* In a Dart script that must call `ds`, alias it:153 `ShellEnvironment()..aliases['ds'] = 'dart run process_run:shell'`.154155## Examples156157### Add a tool directory and a variable for one shell158159```dart160import 'package:process_run/shell.dart';161162Future<void> main() async {163 var env = ShellEnvironment()164 ..paths.prepend('/opt/android/platform-tools')165 ..vars['ANDROID_SERIAL'] = 'emulator-5554';166 var shell = Shell(environment: env, verbose: false);167 var devices = await shell.run('adb devices');168 print(devices.outText);169}170```171172### Minimal, fully controlled environment173174```dart175import 'package:process_run/shell.dart';176177Future<void> main() async {178 var env = ShellEnvironment.empty()179 ..paths.addAll(['/usr/bin', '/bin'])180 ..vars['HOME'] = '/tmp/build-home'181 ..vars['LANG'] = 'C';182 var shell = Shell(environment: env, includeParentEnvironment: false);183 await shell.run('env');184}185```186187### Aliases, including nested ones188189```dart190import 'package:process_run/shell.dart';191192Future<void> main() async {193 var env = ShellEnvironment()194 ..aliases['fvm_flutter'] = 'fvm flutter'195 ..aliases['fbuild'] = 'fvm_flutter build';196 var shell = Shell(environment: env);197 // Runs `fvm flutter build apk --release`.198 await shell.run('fbuild apk --release');199}200```201202### Check a tool from a given environment203204```dart205import 'package:process_run/shell.dart';206207bool hasFirebaseCli(ShellEnvironment env) => env.whichSync('firebase') != null;208209Future<void> main() async {210 var env = ShellEnvironment()..paths.prepend('/home/me/.firebase/tools/bin');211 if (!hasFirebaseCli(env)) {212 print('firebase not found in ${env.paths}');213 return;214 }215 await Shell(environment: env).run('firebase --version');216}217```218219### Scoped default environment with runZoned220221```dart222import 'package:process_run/shell.dart';223224Future<void> buildFlavor(String flavor) => (ShellEnvironment()225 ..vars['FLAVOR'] = flavor)226 .runZoned(() async {227 // Every Shell()/run() created here sees FLAVOR=flavor.228 await run('dart run tool/build.dart');229});230231Future<void> main() async {232 await Future.wait([buildFlavor('dev'), buildFlavor('prod')]);233}234```235236### Persist a variable in the local env.yaml237238```dart239import 'package:process_run/shell.dart';240241Future<void> main() async {242 var shell = Shell(verbose: false);243 // Written to .local/ds_env.yaml, picked up by every future `ds run`244 // and `Shell()` in this directory.245 shell = await shell.shellVarOverride('MY_PROJECT_ID', 'proj-123');246 print(shell.options.environment.vars['MY_PROJECT_ID']); // proj-123247 // Delete it.248 shell = await shell.shellVarOverride('MY_PROJECT_ID', null);249}250```251252### Sample `~/.config/tekartik/process_run/env.yaml`253254```yaml255path:256 - ~/.android/bin257 - ~/.firebase/tools/bin258 - /home/user/Apps/bin259var:260 ANDROID_TOP: ~/.android261 MY_PROJECT_ID: WKDL_456_Q262alias:263 qr: /path/to/my_qr_app264 hello: echo Hello265```266267### Redirect the config files in tests268269```dart270import 'package:process_run/shell.dart';271import 'package:test/test.dart';272273void main() {274 test('isolated env files', () async {275 var env = ShellEnvironment()276 ..vars['TEKARTIK_PROCESS_RUN_USER_ENV_FILE_PATH'] =277 '.dart_tool/test/user_env.yaml'278 ..vars['TEKARTIK_PROCESS_RUN_LOCAL_ENV_FILE_PATH'] =279 '.dart_tool/test/local_env.yaml'280 ..aliases['ds'] = 'dart run process_run:shell';281 var shell = Shell(environment: env, verbose: false);282 await shell.run('ds env var set TEST_VAR 1');283 var out = (await shell.run('ds env var get TEST_VAR')).outText;284 expect(out, contains('TEST_VAR: 1'));285 });286}287```288289## Common mistakes290291* `env.vars['PATH'] = ...`: ignored, `PATH` is only editable through292 `env.paths`.293* Mutating a `ShellEnvironment` after creating the `Shell` and expecting the294 shell to see it: create a new shell (`cloneWithOptions`) instead.295* `includeParentEnvironment: false` with an environment that has no `paths`:296 no executable can be resolved and the child has no `PATH`.297* Assigning the global `shellEnvironment` in a library: it leaks into every298 shell of the application. Use `Shell(environment:)` or `runZoned`.299* Expecting `alias` entries added with `userLoadEnv(aliases:)` to work: only300 `vars` and `paths` are applied; use `ShellEnvironment.aliases` or the301 `env.yaml` `alias:` section.302* Expecting `ds env var set` to affect the current shell object: it edits303 the file; use `shellVarOverride` or create a new `Shell` afterwards.304* Running `ds` on Windows/Linux without `dart pub global activate305 process_run` or the `dart run process_run:shell` prefix.306307## More308309See [references/ds-cli.md](references/ds-cli.md) for the full `ds` command310tree, the `env.yaml` format details and the lower level helpers311(`getUserEnvFilePath`, `getLocalEnvFilePath`, `userConfig`).