12.10. Executing External Commands

Problem

You want to execute an external (system) command from within a Scala application. You’re not concerned about the output from the command, but you are interested in its exit code.

Solution

To execute external commands, use the methods of the scala.sys.process package. There are three primary ways to execute external commands:

  • Use the ! method to execute the command and get its exit status.

  • Use the !! method to execute the command and get its output.

  • Use the lines method to execute the command in the background and get its result as a Stream.

This recipe demonstrates the ! method, and the next recipe demonstrates the !! method. The lines method is shown in the Discussion of this recipe.

To execute a command and get its exit status, import the necessary members and run the desired command with the ! method:

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

scala> "ls -al".!
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
res0: Int = 0

When using the ! method, you can get the exit code of the command that was run:

scala> val exitCode = "ls -al".!
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
result: Int = 0

scala> println(exitCode)
0

Both of those examples work because of an ...

Get Scala Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.