14.4. Running a Shell Command from the REPL

Problem

You want to be able to run a shell command from within the Scala REPL, such as listing the files in the current directory.

Solution

Run the command using the :sh REPL command, then print the output. The following example shows how to run the Unix ls -al command from within the REPL, and then show the results of the command:

scala> :sh ls -al
res0: scala.tools.nsc.interpreter.ProcessResult = `ls -al` (6 lines, exit 0)

scala> res0.show
total 24
drwxr-xr-x   5 Al  staff  170 Jul 14 17:14 .
drwxr-xr-x  29 Al  staff  986 Jul 14 15:27 ..
-rw-r--r--   1 Al  staff  108 Jul 14 15:34 finance.csv
-rw-r--r--   1 Al  staff  469 Jul 14 15:38 process.scala
-rw-r--r--   1 Al  staff  412 Jul 14 16:24 process2.scala

Alternatively you can import the scala.sys.process package, and then use the normal Process and ProcessBuilder commands described in Recipe 12.10:

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

scala> "ls -al" !
total 24
drwxr-xr-x   5 Al  staff  170 Jul 14 17:14 .
drwxr-xr-x  29 Al  staff  986 Jul 14 15:27 ..
-rw-r--r--   1 Al  staff  108 Jul 14 15:34 finance.csv
-rw-r--r--   1 Al  staff  469 Jul 14 15:38 process.scala
-rw-r--r--   1 Al  staff  412 Jul 14 16:24 process2.scala
res0: Int = 0

Scala’s -i option

Although those examples show the correct approach, you can improve the situation by loading your own custom code when you start the Scala interpreter. For instance, I always start the REPL in my /Users/Al/tmp directory, and I have a file in that directory named repl-commands ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.