9

I recently discovered sys.process package in Scala, and was amused by its power.

But when I try to combine it with bash pipes and backticks, I get stuck.

This obviously doesn't work:

scala> "echo `date`" !!
res0: String = "
"`date`
"

I tried to use the bash executable to get the desired behavior:

scala> "bash -e echo `date`" !!
/bin/echo: /bin/echo: cannot execute binary file
java.lang.RuntimeException: Nonzero exit value: 126

What am I doing wrong?

Edit:

scala> "bash -ic 'echo `date`'" !!
`date`': unexpected EOF while looking for matching `''
`date`': syntax error: unexpected end of file
 java.lang.RuntimeException: Nonzero exit value: 1
2
  • Informative example, but I hope you realise you don't need bash at all for this: Seq("date")!! Commented Jan 12, 2016 at 0:14
  • @ToddOwen - sure, that was just for example purposes. Commented Jan 12, 2016 at 8:03

1 Answer 1

22

You're doing multiple things wrong actually. You should be using the -c option of bash and you should be using a Seq[String] with each parameter to bash in its own String, or the scala library will just split the String at every space character. (This is why Rex Kerr's solution doesn't work.)

scala> import sys.process.stringSeqToProcess
import sys.process.stringSeqToProcess

scala> Seq("bash", "-c", "echo `date`")!!
res20: String = 
"Sun Dec 4 16:40:04 CET 2011
"
Sign up to request clarification or add additional context in comments.

2 Comments

Good point about the Seq version. I actually used that one instead, since I always do, and never checked the single-string version!
Here is another example executing a script and with args to follow. IE: test.sh echo $1 scala> Seq("/somePath/test.sh"," HI")! credit due to here: stackoverflow.com/questions/9039167/…

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.