Flutter: Use | symbol in Process.runsync

Issue

I want to use | pipe symbol in command but it is throwing error whenever i use this or any other special symbol like >, >> in commands.

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 gives error

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

If i run this same command in terminal it gives me the output.

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

What am i missing here?
P.S all commands without | symbols run perfectly fine.

EDIT : I gave runInShell argument to true but the problem persists.

Solution

The pipe feature comes from the shell you are using. I thought it would work with runInShell but could not get it to work. Instead, you can do this which will explicit run your commands using /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");
  }
}

Answered By – julemand101

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *