Jus12 Jus12 - 2 months ago 6
Scala Question

Executing shell commands from Scala REPL

An interesting feature of Scala REPL is if you drop any jar in your

%SCALA_HOME%\lib
directory, it is available for import from the REPL. I have several jars there, and I often need to find out which ones are available to be included. So I always have to open another command window and find out which jars exist in that directory. It would be great if the REPL allowed me to execute system commands such as
dir
or
ls
or at least list all the jars in the above lib directory. What is the easiest way (if any) to invoke shell commands in REPL ?

Answer

In REPL the :sh command allow you to introduce shell command:

Windows version:

scala> :sh cmd /C dir
  res0: scala.tools.nsc.interpreter.ProcessResult = `cmd /C dir` (28 lines, exit 0)
scala> res0 foreach println

(unfortunately, there is no way to avoid the call to cmd \C before the shell command)

Unix-like version:

scala> :sh ls
  res0: scala.tools.nsc.interpreter.ProcessResult = `cmd /C dir` (28 lines, exit 0)
scala> res0 foreach println

Update: Inspired by Daniel's answer, a little trick for windows user:

scala> implicit def stringToDosProcess(s: String) =
  scala.sys.process.stringToProcess("cmd /C "+ s)
stringToDosProcess: (s: String)scala.sys.process.ProcessBuilder

scala> "dir".!
Comments