简体   繁体   中英

Scala - shell commands with pipe

I'm a Scala beginner and I'm writing a wrapper for invoking shell commands. Currently I'm trying to invoke shell commands with pipes from a specified directory.

To achieve this I wrote simple utility:

def runCommand(command: String, directory: File): (Int, String, String) = {

  val errbuffer = new StringBuffer();
  val outbuffer = new StringBuffer();

  //run the command
  val ret = sys.process.Process(command, directory) !
  //log output and err
  ProcessLogger(outbuffer append _ + "\n", outbuffer append _ + "\n");

  return (ret, outbuffer.toString(), errbuffer.toString());
}

However with this utility I can't use pipes, for example:

runCommand("ps -eF | grep -i foo", new File("."));

First I thought, that pipes are shell's functionality, so I tried "/bin/sh -c ps -eF | grep -i foo", but it seems that expression from the right of the pipe was ignored.

I also tried running commands with ! syntax (sys.process._ package), but I couldn't figure out, how to call command from specified directory (without using "cd").

Could you please advice me, how to do this correctly?

Change

val ret = sys.process.Process(command, directory) !

to

val ret = sys.process.stringSeqToProcess(Seq("/bin/bash", "-c", "cd " + directory.getAbsolutePath + ";" + command))

Or you could directly use the magic provided by Scala:

import.scala.sys.process._
val ret = "ps -ef" #| "grep -i foo" !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM