Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing bash strings using scala.sys.process

Tags:

bash

scala

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
like image 353
Rogach Avatar asked Dec 04 '11 15:12

Rogach


1 Answers

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
"
like image 143
Kim Stebel Avatar answered Nov 05 '22 03:11

Kim Stebel