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?
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.
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."
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"!!
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" !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With