5

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?

1
  • @xhochy OK. I removed the comment so that nobody can accidentaly use it. :) Commented Oct 7, 2012 at 20:35

1 Answer 1

9

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" !
Sign up to request clarification or add additional context in comments.

6 Comments

Unfortunately it didn't work. I get this error: -eF: -c: line 0: unexpected EOF while looking for matching `'' -eF: -c: line 1: syntax error: unexpected end of file
@altanis Oh, Scala seems to remove the ' ticks sometimes. I updated my answer with a solution that should work (I think the best would be to use the Scala magic where you enter the pipe as a function (the last example).
@altanis - Seems you have a redundant quote in your command. Try printing the directory.getAbsolutePath + ";" + command to output, maybe that would solve it.
@Rogach The first comment of altanis refers to an older answer of mine. In the updated version this problem should be gone.
@xhochy Thanks, now it works correctly. The only thing that I changed is: /bin/bash -> /bin/sh.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.