writeAndRunShellScript function

Progress writeAndRunShellScript(
  1. String scriptContent, {
  2. List<String> args = const [],
  3. Directory? workingDirectory,
  4. Progress? progress,
  5. bool terminal = false,
})

Executes a script by first writing it as file and then running it as shell script

Use args to pass arguments to the script

Use workingDirectory to set the working directory of the script, default to current working directory

When terminal is true (default: false) Stdio handles are inherited by the child process. This allows stdin to read by the script

Implementation

dcli.Progress writeAndRunShellScript(
  String scriptContent, {
  List<String> args = const [],
  Directory? workingDirectory,
  dcli.Progress? progress,
  bool terminal = false,
}) {
  final script = tempExecutableScriptFile(scriptContent);
  final Progress scriptProgress =
      progress ?? Progress(print, stderr: printerr, captureStderr: true);

  try {
    return dcli.startFromArgs(
      script.absolute.path,
      args,
      workingDirectory: workingDirectory?.absolute.path,
      progress: scriptProgress,
      terminal: terminal,
    );
  } catch (e) {
    print(
      "\nError executing script:\n\n"
      "$scriptContent",
    );
    if (progress == null) {
      print(
        "The captured error of running the script is:\n"
        "${scriptProgress.toList().join('\n')}\n",
      );
    }
    rethrow;
  } finally {
    script.deleteSync(recursive: true);
  }
}