view raw
Jus12 Jus12 - 8 months ago 29
Scala Question

Executing shell commands from Scala REPL

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

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
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 ?


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

Windows version:

scala> :sh cmd /C dir
  res0: = `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: = `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".!