颤振:使用 | Process.runsync 中的符号

Flutter: Use | symbol in Process.runsync

我要用 |命令中的管道符号,但每当我在命令中使用此符号或任何其他特殊符号(如>、>>)时都会抛出错误。

import 'dart:io';

main() {
  print("This will work");
  runCommand();
}

void runCommand() {
  try {
    final data = Process.runSync("lscpu", ["|", "grep", "Model Name"]);
    if (data.exitCode == 0) {
      String res = data.stdout.toString();
      List<String> result;
      result = res.split(":");
      print(result[1]);
    } else {
      print("Error while running command   :   ${data.stderr.toString()}");
    }
  } catch (e) {
    print("Catch error $e");
  }
}

这给出了错误

This will work
Error while running command   :   lscpu: bad usage
Try 'lscpu --help' for more information.

如果我 运行 在终端中使用相同的命令,它会给我输出。

ashu@bitsandbytes:~$ lscpu | grep "Model"
Model name:                      Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz

我在这里错过了什么? P.S 所有没有|的命令符号 运行 非常好。

编辑:我将 runInShell 参数设置为 true 但问题仍然存在。

管道功能来自您正在使用的shell。我认为它可以与 runInShell 一起使用,但无法让它工作。相反,您可以执行此操作,这将使用 /bin/sh:

显式 运行 您的命令
import 'dart:io';

main() {
  print("This will work");
  runCommand();
}

void runCommand() {
  try {
    final data = Process.runSync('/bin/sh', ['-c', r'lscpu | grep "Model name"']);

    if (data.exitCode == 0) {
      String res = data.stdout.toString();
      List<String> result;
      result = res.split(":");
      print(result[1]);
    } else {
      print("Error while running command   :   ${data.stderr.toString()}");
    }
  } catch (e) {
    print("Catch error $e");
  }
}