Executing shell commands from Scala REPL

Alternative: use Scala's sys.process library:

scala> import sys.process._
import sys.process._

scala> "ls /home/dcs/scala-2.9.1.final".!
bin
doc
lib
man
meta
misc
src
res1: Int = 0

UPDATE

The means for extracting :sh output has changed over the years.

Welcome to Scala 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_91).
Type in expressions for evaluation. Or try :help.

scala> :sh date
res0: scala.tools.nsc.interpreter.ProcessResult = `date` (1 lines, exit 0)

scala> res0 foreach println
<console>:13: error: value foreach is not a member of scala.tools.nsc.interpreter.ProcessResult
       res0 foreach println
            ^

scala> res0.show
<console>:13: error: value show is not a member of scala.tools.nsc.interpreter.ProcessResult
       res0.show
            ^

scala> res0.lines
res3: List[String] = List(Sat Sep 17 19:29:26 PDT 2016)

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".!

Here is a little-known trick of REPL:

Welcome to Scala version 2.10.0-20120323-101508-45eebcf98d (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).
Type in expressions to have them evaluated.
Type :help for more information.

scala> /home/dcs/scala-2.9.1.final/<TAB>
/home/dcs/scala-2.9.1.final/misc   /home/dcs/scala-2.9.1.final/bin    /home/dcs/scala-2.9.1.final/man    /home/dcs/scala-2.9.1.final/src    /home/dcs/scala-2.9.1.final/lib    
/home/dcs/scala-2.9.1.final/meta   /home/dcs/scala-2.9.1.final/doc    

scala> /home/dcs/scala-2.9.1.final/lib/<TAB>
/home/dcs/scala-2.9.1.final/lib/scala-dbc.jar        /home/dcs/scala-2.9.1.final/lib/scala-swing.jar      /home/dcs/scala-2.9.1.final/lib/jline.jar            
/home/dcs/scala-2.9.1.final/lib/scala-library.jar    /home/dcs/scala-2.9.1.final/lib/scala-compiler.jar   /home/dcs/scala-2.9.1.final/lib/scalap.jar           

scala> /home/dcs/scala-2.9.1.final/lib/scala-library.jar
res0: scala.tools.nsc.io.File = /home/dcs/scala-2.9.1.final/lib/scala-library.jar

Where <TAB> is I pressing tab.

Tags:

Scala