12.11. Executing External Commands and Using STDOUT

Problem

You want to run an external command and then use the standard output (STDOUT) from that process in your Scala program.

Solution

Use the !! method to execute the command and get the standard output from the resulting process as a String.

Just like the ! command in the previous recipe, you can use !! after a String to execute a command, but !! returns the STDOUT from the command rather than the exit code of the command. This returns a multiline string, which you can process in your application:

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

scala> val result = "ls -al" !!
result: String =
"total 64
drwxr-xr-x  10 Al  staff   340 May 18 18:00 .
drwxr-xr-x   3 Al  staff   102 Apr  4 17:58 ..
-rw-r--r--   1 Al  staff   118 May 17 08:34 Foo.sh
-rw-r--r--   1 Al  staff  2727 May 17 08:34 Foo.sh.jar
"

scala> println(result)
total 64
drwxr-xr-x  10 Al  staff   340 May 18 18:00 .
drwxr-xr-x   3 Al  staff   102 Apr  4 17:58 ..
-rw-r--r--   1 Al  staff   118 May 17 08:34 Foo.sh
-rw-r--r--   1 Al  staff  2727 May 17 08:34 Foo.sh.jar

If you prefer, you can do the same thing with a Process or Seq instead of a String:

val result = Process("ls -al").!!
val result = Seq("ls -al").!!

As shown in the previous recipe, using a Seq is a good way to execute a system command that requires arguments:

val output = Seq("ls", "-al").!!
val output = Seq("ls", "-a", "-l").!!
val output = Seq("ls", "-a", "-l", "/tmp").!!

The first element in the Seq is the name of the command to be run, and subsequent ...

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.