Running OS commands
suggest changeDart CLI applications, build scripts, and server backends frequently need to invoke system binaries, execute shell commands, and interact with child processes. The dart:io library provides the Process class to launch, control, and stream data to and from operating system processes.
Simple Execution with Process.run()
Process.run() asynchronously spawns an external process, buffers its standard output and standard error, and completes with a ProcessResult once the process terminates:
import 'dart:io';
void main() async {
// Execute 'git --version'
final result = await Process.run('git', ['--version']);
print('Exit code: ${result.exitCode}');
print('Stdout: ${result.stdout}');
if (result.exitCode != 0) {
stderr.write('Stderr: ${result.stderr}');
}
}
Synchronous Execution (Process.runSync)
For simple, blocking CLI scripts where waiting for a command before continuing is acceptable:
import 'dart:io';
void main() {
final result = Process.runSync('dart', ['--version']);
print('Dart Version Info: ${result.stdout}${result.stderr}');
}
Warning: Avoid
Process.runSync()in Flutter applications or network servers; blocking the main thread freezes the UI and delays event loop handling.
Shell Built-Ins and runInShell
Commands like dir, echo, type, or shell piping (|) are built-in features of your system shell (cmd.exe/PowerShell on Windows, sh/bash on macOS/Linux), rather than standalone executable binaries.
To execute shell built-ins or leverage $PATH environment resolution, set runInShell: true:
import 'dart:io';
void main() async {
// Uses cmd.exe /c on Windows, or /bin/sh -c on Linux/macOS
final result = await Process.run(
'echo',
['Dart is awesome!'],
runInShell: true,
);
// Prints: Dart is awesome!
// (cmd.exe on Windows prints the quotes too: "Dart is awesome!")
stdout.write(result.stdout);
}
Working Directory and Custom Environment Variables
You can specify the execution folder and custom environment variables passed to the child process:
import 'dart:io';
void main() async {
final result = await Process.run(
'git',
['status', '--short'],
workingDirectory: r'D:\src\my-project',
environment: {
'GIT_TERMINAL_PROMPT': '0', // Disable interactive prompts
},
includeParentEnvironment: true, // Retain existing PATH and system vars
);
print(result.stdout);
}
Streaming Long-Running Processes (Process.start)
When running commands that produce continuous output (like build tools, server daemons, or docker logs), buffering all output into memory with Process.run() is undesirable.
Use Process.start() to stream stdout and stderr in real time:
import 'dart:convert';
import 'dart:io';
void main() async {
// Start child process
// ping uses -n for the count on Windows and -c elsewhere
final countFlag = Platform.isWindows ? '-n' : '-c';
final process = await Process.start('ping', [countFlag, '4', '8.8.8.8'], runInShell: true);
// Stream stdout line by line
process.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((line) {
print('[PING]: $line');
});
// Stream stderr
process.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((errLine) {
stderr.writeln('[ERROR]: $errLine');
});
// Wait for the process to exit
final exitCode = await process.exitCode;
print('Ping finished with exit code: $exitCode');
}
Writing to a Process via stdin
You can send interactive input to a running process via process.stdin:
import 'dart:convert';
import 'dart:io';
void main() async {
// Launch an interactive python interpreter
final process = await Process.start('python', ['-i'], runInShell: true);
// Read response
process.stdout.transform(utf8.decoder).listen((output) {
stdout.write(output);
});
// Write commands to python stdin
process.stdin.writeln('print("Hello from Dart child process!")');
process.stdin.writeln('print(2 ** 10)');
process.stdin.writeln('exit()');
await process.stdin.flush();
await process.stdin.close();
final exitCode = await process.exitCode;
print('Process exited with code $exitCode');
}
Process Timeouts and Termination
Guarding processes with timeouts prevents stalled child commands from hanging execution indefinitely:
import 'dart:async';
import 'dart:io';
Future<int> runWithTimeout(String executable, List<String> args, Duration timeout) async {
final process = await Process.start(executable, args);
final timer = Timer(timeout, () {
print('Command timed out! Killing process...');
process.kill(ProcessSignal.sigkill);
});
final exitCode = await process.exitCode;
timer.cancel();
return exitCode;
}
Best Practices
- Pass arguments as a
List<String>: Never concatenate arguments into a single string when executing binaries directly; separate list items prevent command injection vulnerabilities. - Use
runInShell: truejudiciously: Only enablerunInShellwhen invoking shell built-ins or when PATH lookup requires the shell environment. - Always handle non-zero exit codes: Check
result.exitCode == 0before processing output data. - Use
Process.start()for high-volume logs: Prevents allocating gigabytes of buffered memory when running noisy builds or data processing commands.