6

Is there an easy way to do the following in Scala (or Java). I want to run command line commands from a Scala process, for example:

 cd test && javac *.java

as a dynamically generated shell script. The javac *.java should happen in the directory test. The usual simple

 import scala.sys.process._
 ...
 "cd test && javac *.java".!

or

 "cd test && javac *.java".!!

don't work, because Scala misinterpretes the && and the wildcard *. I have no idea why.

Martin Berger
  • 1,120
  • 9
  • 19

2 Answers2

14

For what you want, you should enter the string as a command-line argument to bash. (That is, Process(Seq("bash","-c","cd test && javac *.java")).!) The reason is that there is no virtual shell into which you're entering commands that will change state like cd. You have to create one explicitly.

The process tools will allow you to chain calls together, but the side-effects of the calls had better be reflected in the file system or somesuch, not in the shell environment. The ProcessBuilder scaladoc contains an example at the end of the introductory text.

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • 1
    Thanks, that makes a lot of sense. In the mean time I have found related questions [here](http://stackoverflow.com/questions/11790240/how-to-run-unix-shell-commands-with-wildcards-using-java), [here](http://stackoverflow.com/questions/2111983/java-runtime-getruntime-exec-wildcards) and [here](http://stackoverflow.com/questions/11576767/setting-current-working-directory-when-executing-a-shell-process) that make similar points. I think the Scala documentation could be better on this matter. – Martin Berger Oct 23 '13 at 11:20
1

This should work fine

import scala.sys.process._    

"cd test".#&&("javac *.java").!

Equivalent to

"cd test" #&& "javac *.java" !
maxmithun
  • 1,089
  • 9
  • 18