Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - shell commands with pipe

Tags:

scala

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?

like image 862
Sebastian Łaskawiec Avatar asked Oct 07 '12 20:10

Sebastian Łaskawiec


People also ask

What is the use of pipe in shell script?

The pipe character | is used to connect the output from one command to the input of another. > is used to redirect standard output to a file.

How many commands can you pipe together at a time?

As far as I know, there is no limit on the number of pipes, as the commands are simply executed one after the other. The only limit would be the quantity of data passed in through the pipe, or the "Pipe Buffer Limit."

How do you execute a scala command?

Once this is imported, you'll be able to run your regular shell commands by enclosing the command in double quotes followed by one or two exclamation marks. For example: scala> "ls -lth"! scala> "ls -lth"!!


1 Answers

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" !
like image 107
Uwe L. Korn Avatar answered Sep 22 '22 16:09

Uwe L. Korn